通过使用管道实现两个或多个进程之间的通信。所谓管道,就是将一个进程的标准输出与另一个进程的标准输入联系在一起,进行通信的一种方法。同组进程之间可用无名管道任意通信,而不同组进程之间可通古共有名管道进行通信。
使用无名管道pipe(),进行父子进程之间的通信。
#include <sys/types.h>
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <unistd.h>
int pipe(int filedes[2]);
char parent[] = "A message to pipe's communication.\n";
int main()
{
int pid;
int chanl[2];
char buf[100];
pipe(chanl);
pid = fork();
if(pid < 0)
{
printf("to creat child error\n");
exit(1);
}
if(pid > 0)
{
close(chanl[0]);
printf("parent process sends a message to child.\n");
write(chanl[1],parent,sizeof(parent));
close(chanl[1]);
printf("parent process waits the child to terminate.\n");
wait(0);
printf("parent process terminate.\n");
}
else
{
close(chanl[1]);
read(chanl[0],buf,100);
printf("The message read by child process from parent is :%s.\n",buf);
close(chanl[0]);
printf("child process terminates\n");
}
return 0;
}
分析:父进程首先使用pipe(chanl)系统调用打开一个无名管道,之后创建一个子进程。子进程复制父进程的打开文件表。为了正确通信,父进程关闭读通道close(chanl[0]),子进程关闭写通道close(chanl[1]).父进程向管道写,子进程从管道读。完成一次通信后,父子进程分别关闭自己的读/写通道,管道文件消失。
PS:使用无名管道进行通信时,是使用临时文件的方式实现进程之间的批量数据传输。若通信双方不是父子关系,不能直接建立通信联系,而要有创建他们的共同的父进程为他们创建管道。在通过复制父进程映像使两者之间建立联系