Unix编程。创建了两个命名管道,利用这两个管道实现父子进城的通讯。即父进程可以像子进程发送消息,可以读取子进程的消息。子进程一样。下面是全部源码。
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <err.h>
#include <sys/wait.h>
#include <sys/stat.h>
#include <fcntl.h>
int main(){
char buf[1024]; //缓冲区,用来存放读取的内容。
pid_t pid;//进程标识
char pipe[]="./fifo";
memset(buf,0,sizeof(buf));//清空缓冲区的内容
if(mkfifo(pipe,0660))//0660具有读写权限
{
printf(“创建管道失败!");
exit(1);
}
if((pid=fork())<0)
{
printf(“创建进程失败!");
exit(1);
}
else if(pid==0)//子进程
{
int fd=open(pipe,O_RDWR);
char content[]="这是子进程!\n";
write(fd,content,sizeof(content));
read(fd,buf,sizeof(buf));
printf("子进程收到的消息:%s",buf);
}
else//父进程
{
int fd=open(pipe,O_RDWR);
char content[]="这里是父进程\n";
read(fd,buf,sizeof(buf));
printf("父进程接受的消息: %s",buf);
write(fd,content,sizeof(content));
}
return 0;
}