匿名管道
管道文件的大小始终是为0,更多的时候,它只是起一个标识作用,标识内核中的那块缓存区。就会出现所谓的匿名管道(比如父子进程之间的通信)。
使用pipe创建匿名管道,看不到pipe文件。
pipe(int fds[2]); // fds[0] 读,fds[1]写
返回2个文件描述符,一个读文件描述符,一个写文件描述符。
匿名管道只适用于父子进程
案例:
使用2个子进程,分别计算1-5000的素数,5001-10000的素数。主进程负责保存数据到文件。
pipe.c
#include<stdio.h>
#include<unistd.h>
#include<stdlib.h>
#include<sys/stat.h>
#include<sys/wait.h>
#include<sys/types.h>
#include<fcntl.h>
#include<signal.h>
int numChild = 0; //子进程数全局变量
void childProcEnd(int s)
{
int status;
if(s == SIGCHLD)
{
printf("delete child%d\n",numChild);
numChild++;
wait(&status);
}
if(numChild == 2)
{
printf("all child delete\n");
exit(0);
}
}
int isSushu(int num)
{
int tp = num;
for(int i = 2;i < tp;i++)
{
if(num%i == 0) return 0;
}
return 1;
}
int main()
{
// int fd = mkfifo("num.pipe",0666);
int numProc = 2;
int fds[2]; //fds[0]是读,fds[1]是写
pipe(fds);
int a,b;
signal(SIGCHLD,childProcEnd); /*在一个进程终止或者停止时,将SIGCHLD信号发送给其父进程,
按系统默认将忽略此信号,如果父进程希望被告知其子系统的这种状态,则应捕捉此信号。*/
printf("father id:%d\n",getpid());
while(1)
{
if(numProc == 2)
{
a = 2;
b = 100;
}
if(numProc == 1)
{
a = 101;
b = 200;
}
if(fork() > 0)//在主进程里创建
{
if(--numProc == 0)
break;
}
else
{
close(fds[0]);
for(int i = a;i <= b;i++)
{
if(isSushu(i) == 1)
write(fds[1] ,&i, 4);
}
exit(0);//当子进程事情做完后退出,是退出的子进程而不是父进程
//子进程退出,等待主进程的回收,以防僵死进程
//break;
}
}
{
close(fds[1]); //把写关闭
//写入到文件里面
int wfd = open("result.txt",O_RDWR | O_CREAT);
while(1)
{
int num = 0;
int ret = read(fds[0],&num, 4);
if(ret == 4)
write(wfd,&num,4);
// printf("%d\n",num);
}
}
return 0;
}
查看原文:http://47.100.160.51/wordpress/?p=110
linux管道通信之匿名管道
最新推荐文章于 2023-06-01 20:21:05 发布