作业
有名管道,创建两个发送接收端,父进程写入管道1和管道2,子进程读取管道2和管道1
mkfifo1.c代码
#include <myhead.h>
int main(int argc, const char *argv[])
{
if(mkfifo("./my_fifo1",0664) == -1)
{
perror("mkfifo");
return -1;
}
if(mkfifo("./my_fifo2",0664) == -1)
{
perror("mkfifo");
return -1;
}
return 0;
}
user1.c代码
#include <myhead.h>
int main(int argc, const char *argv[])
{
pid_t pid = fork();
if(pid>0)//父进程写入管道1
{
int send = open("./my_fifo1",O_WRONLY);//父进程写入管道
if(send==-1)
{
perror("open1");
return -1;
}
char buff[1000];
while(1)
{
fgets(buff,sizeof(buff),stdin);//键盘写入数据
buff[strlen(buff)-1]='\0';//去掉手动输入的enter键
write(send,buff,sizeof(buff));
if(strcmp(buff,"quit")==0)
{
break;
}
}
close(send);
wait(NULL);//阻塞回收
//waitpid(-1,NULL,NOHANG);//-1:任意子进程 非阻塞回收
exit(EXIT_SUCCESS);
}
else if(pid==0)//子进程读取管道2
{
int rcv = open("./my_fifo2",O_RDONLY);//只读发送打开
if(rcv==-1)
{
perror("open2");
return -1;
}
char buff[1000];
while(1)
{
read(rcv,buff,sizeof(buff));
if(strcmp(buff,"quit")==0)
{
break;
}
printf("%s\n",buff);
}
close(rcv);
exit(EXIT_SUCCESS);
}
else{
perror("fork");
return -1;
}
return 0;
}
user2.c代码
#include <myhead.h>
int main(int argc, const char *argv[])
{
pid_t pid = fork();
if(pid>0)//父进程写入管道1
{
int send = open("./my_fifo2",O_WRONLY);//父进程写入管道
if(send==-1)
{
perror("open1");
return -1;
}
char buff[1000];
while(1)
{
fgets(buff,sizeof(buff),stdin);//键盘写入数据
buff[strlen(buff)-1]='\0';//去掉手动输入的enter键
write(send,buff,sizeof(buff));
if(strcmp(buff,"quit")==0)
{
break;
}
}
close(send);
wait(NULL);//阻塞回收
//waitpid(-1,NULL,NOHANG);//-1:任意子进程 非阻塞回收
exit(EXIT_SUCCESS);
}
else if(pid==0)//子进程读取管道2
{
int rcv = open("./my_fifo1",O_RDONLY);//只读发送打开
if(rcv==-1)
{
perror("open2");
return -1;
}
char buff[1000];
while(1)
{
read(rcv,buff,sizeof(buff));
if(strcmp(buff,"quit")==0)
{
break;
}
printf("%s\n",buff);
}
close(rcv);
exit(EXIT_SUCCESS);
}
else{
perror("fork");
return -1;
}
return 0;
}
运行结果:
知识梳理
进程间通信