/* * Sample program for pipe system call - No.42 * * pipe - create pipe * * Synopsis * #include * * int pipe(int filedes[2]); * * Description * pipe creates a pair of file descriptors, pointing to a * pipe inode, and places them in the array pointed to by * filedes. filedes[0] is for reading, filedes[1] is for * writing. */ #include #include main() { int fd[2]; int pid; char buf[BUFSIZ]; char *str = "hello, world\n"; if (pipe(fd) == -1) { /* fd[0] is for reading, fd[1] for writing */ perror("pipe"); exit(1); } switch (pid = fork()) { case -1: perror("fork"); exit(1); break; case 0: /* spawn a child process as upstream */ close(fd[0]); /* file descriptor for reading need to be closed */ strncpy(buf, str, strlen(str) + 1); write(fd[1], buf, sizeof buf); break; default: /* parent process works as downstream */ close(fd[1]); /* file descriptor for writing need to be closed */ read(fd[0], buf, sizeof buf); printf("%s", buf); break; } exit(0); }