两个进程的通信:1、管道文件;2、select 多路复用;
ps -elf //查看系统进程 管道,半双工,一端写一端读 |
创建管道文件
mkfifo 1.pipe
Makefile |
a:a.c b.c
gcc a.c -o a
gcc b.c -o b
.PHONY:clean
clean:
rm a b
|
a.c | b.c |
#include<sys/types.h>
#include<sys/stat.h>
#include<fcntl.h>
#include<stdio.h>
int main(int argc,char** argv)
{
int fdw=open(argv[1],O_WRONLY);
printf("fdw=%d\n",fdw);
write(fdw,"hello",5);
return 0;
}
//如果打开读端,但是没有打开对应的写端,进程会卡住,等待写端打开
//管道都是要两端都打开才能正常运行,如果一段打开,一段没有就会阻塞,等待对方打开
|
#include<sys/types.h>
#include<sys/stat.h>
#include<fcntl.h>
#include<stdio.h>
int main(int argc,char** argv)
{
int fdr=open(argv[1],O_RDONLY);
printf("fdr=%d\n",fdr);
char buf[10]="";
read(fdr,buf,sizeof(buf));
printf("buf=%s\n",buf);
return 0;
}
//打开顺序是先打开写端,在打开写读端
|
如果管道写端关闭,读端如果read,会返回0
改进a.c //同时打开两个管道 | 改进b.c |
#include<sys/types.h>
#include<sys/stat.h>
#include<fcntl.h>
#include<unistd.h>
#include<strings.h>
#include<stdio.h>
#include<string.h>
int main(int argc,char** argv)
{
int fdw=open(argv[1],O_WRONLY);
int fdr=open(argv[2],O_RDONLY);
printf("fdr=%d fdw=%d\n",fdr,fdw);
char buf[128]="";
while(1) //如果管道写端关闭,读端如果read,会返回0
{
bzero(buf,sizeof(buf));
read(0,buf,sizeof(buf));
write(fdw,buf,strlen(buf)-1); //去掉标准输入最后读到的回车
bzero(buf,sizeof(buf));
read(fdr,buf,sizeof(buf));
printf("b:%s\n",buf);
}
return 0;
}
|
#include<sys/types.h>
#include<sys/stat.h>
#include<fcntl.h>
#include<unistd.h>
#include<strings.h>
#include<stdio.h>
#include<string.h>
int main(int argc,char** argv)
{
int fdr=open(argv[1],O_RDONLY);
int fdw=open(argv[2],O_WRONLY);
printf("fdr=%d fdw=%d\n",fdr,fdw);
char buf[128]="";
while(1)
{
bzero(buf,sizeof(buf));
read(fdr,buf,sizeof(buf));
printf("a:%s\n",buf);
bzero(buf,sizeof(buf));
read(0,buf,sizeof(buf));
write(fdw,buf,strlen(buf)-1); //去掉标准输入最后读到的回车
}
return 0;
}
|
//只能你读一句我读一句,不然会卡住