首先给大家分享一下学习视频的地址:
确实是牛客网免费的课,但是我不知道为什么在页面里面找不到,所以就附上网址,大家点击进入就好!
然后如果本文有帮助到你,请给我免费点赞收藏关注,这是我写文章的最大动力!
在2.16视频的末尾,老师提到可以用fork创建子进程,实现读写互相不受限,所以就实现了一下,代码如下:
需要注意的是,我在子进程中做了次数限制,因为想用一下waitpid回收子进程,但是好像写的又不太对,如果有大佬还请指教!
进程A的:
// 有名管道一定要两边都有读写以后才会向下执行,不然就会阻塞
#include<stdio.h>
#include<unistd.h>//access
#include<sys/types.h>//mkfifo
#include<sys/stat.h>//mkfifo
#include<stdlib.h>//read
#include<fcntl.h>//open
#include<string.h>//memset
#include <sys/wait.h>//waitpid
int main(){
//判断是否有管道文件
int ret=access("fifo1",F_OK);
if (ret == -1)
{
printf("管道不存在,创建对应管道!\n");
ret = mkfifo("fifo1",0664);
if (ret == -1)
{
perror("mkfifo");
exit(-1);
}
}
ret=access("fifo2",F_OK);
if (ret == -1)
{
printf("管道不存在,创建对应管道!\n");
ret = mkfifo("fifo2",0664);
if (ret == -1)
{
perror("mkfifo");
exit(-1);
}
}
pid_t pid=fork();
if (pid > 0)
{
/* 父进程read */
int fdr = open("fifo2",O_RDONLY);
if (fdr == -1 )
{
perror("open");
exit(-1);
}
printf("打开fifo2成功,等待读取...\n");
char buff[128];
memset(buff,0,128);
while (1)
{
memset(buff, 0, 128);
ret = read(fdr, buff, 128);
if (ret <= 0)
{
perror("read");
exit(0);
}
printf("B: %s\n", buff);
ret = waitpid(pid,NULL,WNOHANG);
if (ret > 0)
{
printf("子进程死掉,所以父进程也退出!");
exit(0);
}
}
close(fdr);
}
else{//子进程写
int fdw = open("fifo1",O_WRONLY);
if (fdw == -1 )
{
perror("open");
exit(-1);
}
printf("打开fifo1成功,等待写入...\n");
char buff[128];
memset(buff,0,128);
int i=3;
while (i--)
{
memset(buff,0,128);
fgets(buff,128,stdin);
ret = write(fdw,buff,strlen(buff));
if (ret == -1)
{
perror("write");
exit(0);
}
}
printf("三次写用完了,所以A子进程关闭!");
close(fdw);
}
return 0;
}
进程B的:
// 有名管道一定要两边都有读写以后才会向下执行,不然就会阻塞
#include<stdio.h>
#include<unistd.h>//access
#include<sys/types.h>//mkfifo
#include<sys/stat.h>//mkfifo
#include<stdlib.h>//read
#include<fcntl.h>//open
#include<string.h>//memset
#include <sys/wait.h>//waitpid
int main(){
//判断是否有管道文件
int ret=access("fifo1",F_OK);
if (ret == -1)
{
printf("管道不存在,创建对应管道!\n");
ret = mkfifo("fifo1",0664);
if (ret == -1)
{
perror("mkfifo");
exit(-1);
}
}
ret=access("fifo2",F_OK);
if (ret == -1)
{
printf("管道不存在,创建对应管道!\n");
ret = mkfifo("fifo2",0664);
if (ret == -1)
{
perror("mkfifo");
exit(-1);
}
}
pid_t pid=fork();
if (pid > 0)
{
/* 父进程read */
int fdr = open("fifo1",O_RDONLY);
if (fdr == -1 )
{
perror("open");
exit(-1);
}
printf("打开fifo1成功,等待读取...\n");
char buff[128];
memset(buff,0,128);
while (1)
{
memset(buff, 0, 128);
ret = read(fdr, buff, 128);
if (ret <= 0)
{
perror("read");
exit(0);
}
printf("A: %s\n", buff);
ret = waitpid(pid,NULL,WNOHANG);
if (ret > 0)
{
printf("子进程死掉,所以父进程也退出!");
exit(0);
}
}
close(fdr);
}
else{//子进程写
int fdw = open("fifo2",O_WRONLY);
if (fdw == -1 )
{
perror("open");
exit(-1);
}
printf("打开fifo2成功,等待写入...\n");
char buff[128];
memset(buff,0,128);
int i=3;
while (i--)
{
memset(buff,0,128);
fgets(buff,128,stdin);
ret = write(fdw,buff,strlen(buff));
if (ret == -1)
{
perror("write");
exit(0);
}
}
printf("三次写用完了,所以B子进程关闭!");
close(fdw);
}
return 0;
}