Skip to content

Instantly share code, notes, and snippets.

@panta
Last active January 31, 2022 18:19
Show Gist options
  • Save panta/937ca88380b82df1ebc34e36df3bb95a to your computer and use it in GitHub Desktop.
Save panta/937ca88380b82df1ebc34e36df3bb95a to your computer and use it in GitHub Desktop.
Example showing how to
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>
#include <errno.h>
#include <sys/wait.h>
const char *handle_child_process_output(const char *buffer, ssize_t count) {
// we just print it, but we could do any other processing here...
write(STDOUT_FILENO, buffer, (size_t)count);
return buffer;
}
int main() {
/*
* 1. Create a pipe
* 2. Within the child, connect the write end (entrance) of the pipe to STDOUT_FILENO
* 3. Within the child, close the original ends of the pipe
* 4. Within the parent, close the write end (exit) of the pipe
* 5. Read the child ouput from the read end
*/
int filedes[2];
if (pipe(filedes) < 0) {
perror("pipe");
exit(1);
}
pid_t pid = fork();
if ((int)pid < 0) {
/* ERROR */
perror("fork");
exit(1);
} else if (pid == 0) {
/* CHILD */
// connect the read end to stdout
while ((dup2(filedes[1], STDOUT_FILENO) == -1) && (errno == EINTR)) {}
// close the write end
close(filedes[1]);
// close the read end
close(filedes[0]);
execlp("ls", "ls", "-l", (char*)0);
perror("execl");
exit(1);
} else {
/* PARENT */
// close the write end
close(filedes[1]);
// read child ouput
char buffer[4096];
while (1) {
ssize_t count = read(filedes[0], buffer, sizeof(buffer));
if (count == -1) {
if (errno == EINTR) {
continue;
} else {
perror("read");
exit(1);
}
} else if (count == 0) {
break;
} else {
// process child output
handle_child_process_output(buffer, count);
}
}
close(filedes[0]);
wait(0);
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment