/* dup.c * * Parent piping to a child where child spawns using new stdin * */ #include #include #include #include #include extern char **environ; int main(int argc, char **argv) { pid_t pid; int stat_loc; char *str = "all base are belong to us"; int pfds[2]; int ret; if (pipe(pfds) == 0) { pid = fork(); if (pid == -1) { perror("fork"); exit(EXIT_FAILURE); } if (pid) /* parent */ { close(1); /* break the link to stdout, dup2 already kills this but meh */ dup2(pfds[1], 1); /* redirect stdout to pfds[1] */ close(pfds[1]); /* new stdout has been setup above, pfds[1] can be closed */ close(pfds[0]); /* parent will not be reading anything from out pipe */ printf("parent sends out: \"%s\"\n", str); fflush(stdout); /* printf is buffered! */ close(1); /* close stdin or else the child would not know that he's done reading */ ret = waitpid(pid, &stat_loc, WCONTINUED); } else /* child */ { close(0); /* break the link to stdin */ dup2(pfds[0], 0); /* redirect stdin to pfds[0] */ close(pfds[0]); /* new stdin has been setup above, pfds[1] can be closed */ close(pfds[1]); /* parent will not be writing anything into our pipe */ /* here the child will use a redefined stdin */ execlp("wc", "wc", NULL); /* if there wasn't a spawn then we would need to close stdin */ } } else { perror("pipe"); exit(EXIT_FAILURE); } ret = ret; /* hush the dumb compiler */ close(pfds[0]); close(pfds[1]); return 0; }