实现进程收发功能
1.create.c
#include <head.h>
int main(int argc, const char *argv[])
{
if(mkfifo("myfifo",0664)!=0)
{
perror("");
return -1;
}
if(mkfifo("myfifo1",0664)!=0)
{
perror("");
return -1;
}
printf("文件创建成功\n");
getchar();
system("rm a_send_b b_send_a");
return 0;
}
2.snd.c
#include <head.h>
int main(int argc, const char *argv[])
{
pid_t pid;
pid=fork();
if(pid>0)
{
//父进程,发送数据
char wbuf[20];
int fd_send=-1;
if((fd_send=open("./myfifo",O_WRONLY))==-1)
{
perror("");
return -1;
}
while(1)
{
bzero(wbuf,sizeof(wbuf));
printf("请输入:");
fflush(stdout);
read(0,wbuf,sizeof(wbuf));
wbuf[strlen(wbuf)-1]='\0';
write(fd_send,wbuf,sizeof(wbuf));
if(strcmp(wbuf,"quit")==0)
{
break;
}
}
}
else if(pid==0)
{
//子进程,接受数据
char rbuf[20];
int fd_rec=-1;
if((fd_rec=open("./myfifo1",O_RDONLY))==-1)
{
perror("");
return -1;
}
while(1)
{
bzero(rbuf,sizeof(rbuf));
read(fd_rec,rbuf,sizeof(rbuf));
if(strcmp(rbuf,"quit")==0)
{
break;
}
printf("接收到的数据:%s\n",rbuf);
}
exit(EXIT_SUCCESS);
}
wait(NULL);
return 0;
}
3.recv.c
#include <head.h>
int main(int argc, const char *argv[])
{
//以只写的形式打开管道文件
int rfd = -1;
if((rfd = open("./myfifo", O_RDONLY)) == -1)
{
perror("open error");
return -1;
}
int rfd = -1;
if((rfd = open("./myfifo1", O_RDONLY)) == -1)
{
perror("open error");
return -1;
}
printf("读端打开成功\n");
//从管道文件中循环读取数据
char rbuf[128] = "";
while(1)
{
bzero(rbuf, sizeof(rbuf)); //清空内容
//从管道中读取数据
read(rfd, rbuf, sizeof(rbuf));
printf("收到消息:%s\n", rbuf);
//判断
if(strcmp(rbuf, "quit") == 0)
{
break;
}
}
//关闭文件
close(rfd);
return 0;
}