The contents of this page are licensed under the following license
Operating System
Unnamed pipe |
#include <stdio.h> #include <unistd.h> int main() { int fd[2]; /* create pipe */ pipe(fd); /* create child process */ switch (fork()) { case -1:/* error */ perror("fork - can't create process"); break; case 0 :/* child process */ close(1); //close standard output close(fd[0]); //write-only pipe dup(fd[1]); //duplicate fd[1] /* execute ls command */ if (!fork()) execlp("ls", "ls", NULL); else { wait(); close(fd[1]); } break; default:/* parent process */ close(0); //close standard input close(fd[1]); //read-only pipe dup(fd[0]); //dupliactate fd[0] /* execute wc command */ if (!fork()) execlp("wc", "wc", NULL); else { wait(); close(fd[0]); } } } |
Named pipe (FIFO queue) |
#include <stdio.h> #include <fcntl.h> #include <unistd.h> int main() { int fd; /* make named pipe (FIFO) */ mkfifo("fifo", 0600); /* create child process */ switch (fork()) { case -1:/* error */ perror("fork - can't create process"); break; case 0 :/* child process */ close(1); //close standard output fd = open("fifo", O_WRONLY); //open named pipe (FIFO) dup(fd); //duplicate fd /* execute ls command */ if (!fork()) execlp("ls", "ls", NULL); else { wait(); close(fd); } break; default:/* parent process */ close(0); //close standard input fd = open("fifo", O_RDONLY); //open named pipe (FIFO) dup(fd); //dupliactate fd /* execute wc command */ if (!fork()) execlp("wc", "wc", NULL); else { wait(); close(fd); unlink("fifo"); } } } |
August, 23rd 2006 © Michał Kalewski