编写程序实现以下功能:
利用有名管道文件实现进程间通信
要求写进程向有名管道文件写入10次“hello world”
读进程读取有名管道文件中的内容,并依次打印。
有名管道的特点:
1.有名管道支持读写操作,并且存在于文件系统中
2.能够使用使用read和write直接对有名管道进行操作。
3.有名管道是双向管道。
4.可以用于任意进程间的通信,不像匿名管道具有局限性。
我们能够像操作一个文件一样操作有名管道。
实验代码:
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <unistd.h>
#include <sys/stat.h>
int main()
{
int pid,fd;
if(mkfifo("fifotest",0666) < 0)
perror("mkfifo");
pid = fork();
if(pid < 0)
perror("fork");
else if(pid == 0)
{
printf("This is the write process!\n");
int fd = open("fifotest",0666);
for(int i = 0; i < 10;i++)
{
if(write(fd,"hello world",12) < 0)
perror("write");
sleep(1);
}
close(fd);
}
else
{
char str[128];
printf("This is the read process!\n");
int fd1 = open("fifotest",0666);
for(int i = 0;i < 10;i++)
{
if(read(fd1,str,128) < 0)
perror("read");
else
printf("%s\n",str);
}
system("rm -f fifotest");
}
}
实验结果:
实验完成。