有名管道,创建两个发送接收端,父进程写入管道1和管道2,子进程读取管道2和管道1.
代码展示
send.c
#include <myhead.h>
int main(int argc, const char *argv[])
{
pid_t pid = fork();
if(pid > 0){
int send;
send = open("./my_fifo",O_WRONLY);
if(send == -1){
perror("open send");
return -1;
}
char buff[1024];
while(1){
memset(buff,0,sizeof(buff));
int len = read(0,buff,sizeof(buff));
write(send,buff,len);
if(strcmp(buff,"quit\n")==0){
break;
}
}
close(send);
exit(EXIT_SUCCESS);
}else if(pid == 0){
int rev;
rev = open("./my_fifo1",O_RDONLY);
if(rev == -1){
perror("open rev");
return -1;
}
char buff1[1024];
while(1){
memset(buff1,0,sizeof(buff1));
int len = read(rev,buff1,sizeof(buff1));
write(1,buff1,len);
if(strcmp(buff1,"quit\n")==0){
break;
}
}
close(rev);
exit(EXIT_SUCCESS);
}else {
perror("fork");
return -1;
}
return 0;
}
rev.c
#include <myhead.h>
int main(int argc, const char *argv[])
{
pid_t pid = fork();
if(pid > 0){
int rev;
rev = open("./my_fifo",O_RDONLY);
if(rev == -1){
perror("open rev");
return -1;
}
char buff[1024];
while(1){
memset(buff,0,sizeof(buff));
int len = read(rev,buff,sizeof(buff));
write(1,buff,len);
if(strcmp(buff,"quit\n")==0){
break;
}
}
close(rev);
exit(EXIT_SUCCESS);
}else if(pid == 0){
int send;
send = open("./my_fifo1",O_WRONLY);
if(send == -1){
perror("open send");
return -1;
}
char buff1[1024];
while(1){
memset(buff1,0,sizeof(buff1));
int len = read(0,buff1,sizeof(buff1));
write(send,buff1,len);
if(strcmp(buff1,"quit\n")==0){
break;
}
}
close(send);
exit(EXIT_SUCCESS);
}else {
perror("fork");
return -1;
}
return 0;
}
pipe.c
#include <myhead.h>
int main(int argc, const char *argv[])
{
if(mkfifo("./my_fifo",0664)==-1){
perror("mkfifo");
return -1;
}
if(mkfifo("./my_fifo1",0664)==-1){
perror("mkfifo1");
return -1;
}
return 0;
}
运行结果
![在这里插入图片描述](https://i-blog.csdnimg.cn/direct/be16a6bba2254d4fad672546d88f6e11.png)
练习SIGQUIT信号
代码展示
#include <myhead.h>
void sig_son(int s){
if(s == SIGQUIT){
printf("用户按下了ctrl +\\键\n");
}
}
int main(int argc, const char *argv[])
{
if(signal(SIGQUIT,sig_son)==SIG_ERR){
perror("signal");
return -1;
}
while(1){
printf("我真的还想再活500年\n");
sleep(1);
}
return 0;
}
运行结果
![在这里插入图片描述](https://i-blog.csdnimg.cn/direct/2e43e7e41c1842ffbb06ec32031cd8b6.png)
今日思维导图
![在这里插入图片描述](https://i-blog.csdnimg.cn/direct/cb7bc49c54514468be86e75d0822109f.png#pic_center)