今天和大家分享一下进程通信—命名管道。
命名管道和匿名管道的性质基本一致(上篇博客有详细描述,不在此再做说明),区别是命名管道可满足任意两个进程之间的通信。
接着,说明命名管道任意两个进程的通信过程:
a.由进程A利用mkfifo建立管道文件mypipe.
b.进程A以读(或者写)的方式打开管道文件mypipe,一直读(或者写)。
c.进程B以写(或者读)的方式打开管道文件mypipe,一直写(或者读)。
d.当写(或者读)的任意一方进程退出(关闭管道文件),另外一方进程接受到相应信号后退出。
代码运行截图:
Serve.c
client.c
Makefile
运行界面如下:
元代码如下:
namepipe.h
#include<stdio.h>
#include<unistd.h>
#include<sys/types.h>
#include<sys/stat.h>
#include<fcntl.h>
#include<stdlib.h>
int main(){
umask(0);
if(mkfifo("./mypipe", S_IFIFO|0666)<0){
perror("mkfifo error!\n");
exit(-1);
}
int fd = open("./mypipe", O_RDONLY);
if(fd<0){
perror("open wronng!");
exit(-2);
}
char buf[1024];
while(1){
buf[0] = 0;
ssize_t s = read(fd, buf, sizeof(buf)-1);
if(s>0){
buf[s] = 0;
printf("parent:%s\n", buf);
}
else if(s == 0){//child quit,so parent will quit
close(fd);
printf("child quit,so parent will quit!\n");
break;
}
else{//wrong
close(fd);
exit(3);
}
}
return 0;
}
client.c
#include<stdio.h>
#include<unistd.h>
#include<sys/types.h>
#include<sys/stat.h>
#include<fcntl.h>
#include<stdlib.h>
#include<string.h>
int main(){
char buf[1024];
int fd = open("./mypipe",O_WRONLY );
if(fd <0)
{
perror("open wronng!");
exit(-2);
}
while(1){
buf[0] = 0;
printf("please write:");
fflush(stdout);
ssize_t s = read(0, buf, sizeof(buf)-1);
if(s>0)
{
buf[s-1] = 0;
write(fd, buf, strlen(buf));
}
}
close(fd);
return 0;
}
Makefile
.PHONY:all
all:client serve
client:client.c
gcc -o client client.c
serve:namepipe.c
gcc -o serve namepipe.c
.PHONY:clean
clean:
rm -f client serve mypipe
分享如上,望共同进步!