diff options
author | Joseph Hunkeler <jhunkeler@gmail.com> | 2023-11-20 10:06:37 -0500 |
---|---|---|
committer | Joseph Hunkeler <jhunkeler@gmail.com> | 2023-11-20 10:06:37 -0500 |
commit | 228ba2d6a6967e1eabd23c956e27a2e9ebba52d6 (patch) | |
tree | f14c7847d646c9045c2810250c8039d9cedc2f33 /src/system.c | |
parent | 243d8540b3869f9ace2baf8b00f9cb86e8d84d52 (diff) | |
download | stasis-228ba2d6a6967e1eabd23c956e27a2e9ebba52d6.tar.gz |
Add shell_output() and use xmkstemp()
Diffstat (limited to 'src/system.c')
-rw-r--r-- | src/system.c | 44 |
1 files changed, 36 insertions, 8 deletions
diff --git a/src/system.c b/src/system.c index 94a96c0..b819615 100644 --- a/src/system.c +++ b/src/system.c @@ -84,20 +84,16 @@ int shell2(struct Process *proc, char *args) { status = 0; errno = 0; - char t_name[PATH_MAX]; - strcpy(t_name, "/tmp/ohmycal.XXXXXX"); - int fd = mkstemp(t_name); - - FILE *tp; - tp = fdopen(fd, "w"); - if (!tp) { + FILE *tp = NULL; + char *t_name; + t_name = xmkstemp(&tp); + if (!t_name || !tp) { return -1; } fprintf(tp, "#!/bin/bash\n%s\n", args); fflush(tp); fclose(tp); - close(fd); chmod(t_name, 0755); pid = fork(); @@ -207,3 +203,35 @@ int shell_safe(struct Process *proc, char *args[]) { } return result; } + +char *shell_output(const char *command) { + const size_t initial_size = OMC_BUFSIZ; + size_t current_size = initial_size; + char *result = NULL; + char line[OMC_BUFSIZ]; + FILE *pp; + pp = popen(command, "r"); + if (!pp) { + return NULL; + } + result = calloc(initial_size, sizeof(result)); + while (fgets(line, sizeof(line) - 1, pp) != NULL) { + size_t result_len = strlen(result); + size_t need_realloc = (result_len + strlen(line)) > current_size; + if (need_realloc) { + current_size += initial_size; + char *tmp = realloc(result, sizeof(*result) * current_size); + if (!tmp) { + return NULL; + } else if (tmp != result) { + result = tmp; + } else { + fprintf(SYSERROR); + return NULL; + } + } + strcat(result, line); + } + pclose(pp); + return result; +}
\ No newline at end of file |