关于mkfifo()与open()的使用方法?
发布网友
发布时间:2022-07-07 14:42
我来回答
共1个回答
热心网友
时间:2023-10-09 11:55
父子进程通信要一个管道就行了!
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <errno.h>
//#define LUCY "/tmp/lucy"
#define LILEI "/tmp/lilei"
int main(int argc, char *argv[])
{
int fd_lucy,fd_lilei;
char buf_lucy[100],buf_lilei[100];
pid_t pid;
pid=fork();
if(pid==0)
if(pid==0)
{
unlink(LILEI);
if(mkfifo(LILEI,O_CREAT|O_EXCL|0777)<0)
printf("mkfifo lilei error\n");
if((fd_lilei=open(LILEI,O_RDONLY|O_NONBLOCK,0))<0)
printf("open lilei error\n");
while(1)
{
memset(buf_lilei,0,sizeof(buf_lilei));
read(fd_lilei,buf_lilei,sizeof(buf_lilei));
if(strlen(buf_lilei)>0)
printf("lilei:%s\n",buf_lilei);
fflush(stdout);
sleep(1);
}
}
if(pid>0)
{
sleep(2);
//unlink(LUCY);
//if(mkfifo(LUCY,O_CREAT|O_EXCL|0777)<0)
//printf("mkfifo lucy error\n");
if((fd_lucy=open(LILEI,O_WRONLY|O_NONBLOCK,0))==-1)
{
printf("open lucy error\n");
perror("open");
}
while(1)
{
printf("lucy:");
fgets(buf_lucy,sizeof(buf_lucy),stdin);
printf("\n");
write(fd_lucy,buf_lucy,strlen(buf_lucy));
}
}
return 0;
}