Pipelines are the oldest form of IPC for UNIX systems, and all UNIX systems provide such communication mechanisms. The pipeline has the following two limitations:
(1) Historically, pipelines are half-duplex (i.e. data can only flow in one direction).
(2) Pipelines can only be used between two processes with a common ancestor. Typically, a pipeline is created with a process that can be used between parent and child processes after the process calls fork.
Pipeline creation:
The pipeline is created by calling the pipe function.
Header files: #include <unistd.h>
Prototype: int pipe (int fd[2])
Return value: Succeeded, returned 0, failed, returned-1.
Return two file descriptor via parameter FD: fd[0] Open for Read, fd[1] for write. The output of fd[1] is the input of fd[0].
The illustrations are as follows:
Test procedure:
1#include <stdio.h>2#include <unistd.h>3#include <stdlib.h>4 5 intMainintargcChar*argv[])6 {7 intN;8 intfd[2];9 pid_t pid;Ten Charbuf[ -] = {0}; One A if(Pipe (FD) <0) - { -printf"Pipe error\n"); the return-1; - } - - if(PID = fork ()) <0) + { -printf"Fork error\n"); + return-1; A } at Else if(PID >0) - { -Close (fd[0]); -printf"parent Process id:%d, child process id:%d\n", Getpid (), PID); -Write (fd[1],"Hello world\n",sizeof("Hello world\n")); - } in Else - { toClose (fd[1]); +n = Read (fd[0],buf,sizeof(BUF)); -printf"Child process id:%d\n", Getpid ()); theWrite (Stdout_fileno,"Child process:",sizeof("Child process:")); * write (stdout_fileno,buf,n); $ }Panax Notoginseng - return 0; the +}
View Code
Leak check: interprocess communication (IPC): Piping