Ubuntu下Linux进程间通信——匿名管道
Linux提供了多种进程间通信的方法,常见有管道(匿名)、FIFO(有名管道)、消息队列、信号量、共享内存,socket通信。
1.匿名管道
匿名管道是最古老的进程间通信方法,两个进程间管道传递数据是单向的。
#include <unistd.h>
int pipe(int filedes[2]);
filedes会返回两个文件描述符,filedes[0]为读端,filedes[1]为写端。创建成功pipe()会返回0,失败返回-1。
实例
#include <sys/types.h>
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
int fd[2];
int fd1[2];
pid_t pid;
char buf[64]="I am parent process!\n";
char line[64];
//创建管道
if(0!=pipe(fd))
{
fprintf(stderr,"Fail to create pipe!\n");
return 0;
}
//创建进程
pid=fork();
if(pid<0)
{
fprintf(stderr,"Fail to create process!\n");
return 0;
}
//父进程
else if(0<pid)
{
close(fd[0]);
write(fd[1],buf,strlen(buf));
close(fd[1]);
}
//子进程
else
{
close(fd[1]);
read(fd[0],line,64);
printf("DATA From Parent :%s\n",line);
close(fd[0]);
}
return 0;
}
匿名管道通信只能单向通信。父进程向子进程写数据。同一时刻,父进程只能向子进程写入数据,或者读出数据。