#include #include #include #include #include /* Remember to free the returned pointer */ char* getoutput(char *command){ size_t space = 16; char *output = malloc(space); int pipe_ends[2]; // pipefd[0] is the read end, pipefd[1] is the write end pipe(pipe_ends); pid_t pid = fork(); if(pid) { // We're the parent close(pipe_ends[1]); size_t position = 0; ssize_t readlen; while((readlen = read(pipe_ends[0], output + position, 16)) > 0 ){ position += readlen; output = realloc(output, space + 16); space += 16; } output[position] = 0; wait(NULL); return output; } else { // We're the child dup2(pipe_ends[1], 1); execl("/bin/sh", "sh", "-c", command, NULL); printf("This won't happen\n"); exit(1); } } int main(){ char *cmd_output = getoutput("uptime"); printf("The output: %s\n", cmd_output); free(cmd_output); return 0; }