#include #include #include char* getoutput(char* command){ // We'll need a pipe to put the output into // The command will have to run, and put output into the pipe // We'll have to read from the pipe int pipe_fds[2]; char *buffer = malloc(16); pipe(pipe_fds); pid_t child = fork(); if(!child){ // Command part: // 1. Do plumbing as needed to send output into the pipe // 2. Run the command dup2(pipe_fds[1], 1); execl("/bin/sh", "sh", "-c", command, (char *) 0); } else { // Capture part: // 1. Wait for the command to run // 2. Collect the output from the pipe // while there's more to read: // read more stuff size_t sofar = 0; close(pipe_fds[1]); for(;;) { ssize_t readlen = read(pipe_fds[0], buffer + sofar, 16); if(readlen <= 0) break; sofar += readlen; buffer = realloc(buffer, sofar + 16); } buffer[sofar] = 0; // printf("We read: %s\n", buffer); return buffer; } } int main(){ char* output; output = getoutput("who | grep seth"); printf("Output: %s\n", output); free(output); return 0; }