管道通信
匿名管道
#include <unistd.h>
int pipe(int pfd[2]);
pfd[0]用于读管道,而pdf[1]用于写管道。
注意:匿名管道只能用于亲缘关系的进程之间通信。管道通道是单向的,一边读,另一边写。管道可以用于大于两个进程共享。
例如设计父进程读,两个子进程写的代码如下:
#include<stdio.h>
#include<pthread.h>
#include<stdlib.h>
#include<unistd.h>
#include<string.h>
int main(int argc, char* argv)
{
int pipegd[2];
int i;
char buf[19]={
0};
pid_t pid;
pid_t pid1;
int pi = pipe(pipegd);
if(pi<0)
{
perror("pipe:");
return -1;
}
pid=fork();
if(pid<0)
{
perror("pid create:");
return 0;
}
else if(pid == 0)
{
close(pipegd[0]);
memset(buf, 0, 19);
strcpy(buf, "this is b");
write(pipegd[1], buf, strlen(buf));
}
else if(pid>0)
{
pid1=fork();
if(pid1<0)
{
perror("pid create:");
return 0;
}
else if(pid1 == 0)
{
close(pipegd[0]);
memset(buf, 0, 19);
strcpy(buf, "this is a");
write(pipegd[1], buf, strlen(buf));
}
else if(pid1>0)
{
sleep(1);
close(pipegd[1]);
memset(buf,0,19);
read(pipegd[0],buf,19);
printf("pipe re