#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <unistd.h>
#include <sys/stat.h>
/*
3.编写程序实现以下功能:
利用有名管道文件实现进程间通信,要求
写进程向有名管道文件写入10次“hello world”;
读进程读取有名管道文件中的内容,并依次打印。
*/
int main() {
int pid ,fd;
/*
基本函数
int mkfifo(const char * pathname, mode_t mode);
参数说明
pathname:创建的FIFO名字
mode:规定FIFO的读写权限
返回值
成功时返回0
失败时返回-1
若路径名存在,则返回EEXIST错误
说明
一般文件的I/O函数都可用于管道,如open(), close(), read(), write()等。
————————————————
*/
if(mkfifo("fifotest" ,0666)< 0)
perror(" mnkfifo" );
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");
}
}