Skip to content

Instantly share code, notes, and snippets.

@OrangeTide
Last active May 14, 2018 17:44
Show Gist options
  • Save OrangeTide/024cf7a578e04623ed575c50b9462909 to your computer and use it in GitHub Desktop.
Save OrangeTide/024cf7a578e04623ed575c50b9462909 to your computer and use it in GitHub Desktop.
demonstration of using pipe() and fork() to redirect
#define _XOPEN_SOURCE 700
#define _POSIX_C_SOURCE 200809L
#include <stdio.h>
#include <unistd.h>
int main() {
int s, fd[2];
pipe(fd);
if (!fork()) { /* child */
dup2(fd[0], STDIN_FILENO);
close(fd[0]); // not that critical, just a waste
close(fd[1]); // we must close() this copy that the server can close it's end point to signal that 'cat' should terminate
printf("child pid:%d\n", getpid());
execl("/bin/cat", "cat", NULL);
perror("cat");
return 1;
} else { /* parent */
int i;
pid_t child;
close(fd[0]); // not that critical, just a waste
return 1;
} else { /* parent */
int i;
pid_t child;
close(fd[0]); // not that critical, just a waste
for (i = 1; i <= 3; i++) {
dprintf(fd[1], "Counting %d ...\n", i);
sleep(1);
}
close(fd[1]); // we should expect 'cat' to terminate now
child = wait(&s);
if (child < 0)
perror("wait()");
else
printf("child(%d) status:%#X\n", child, s);
}
printf("done!\n");
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment