在上述练习的前提下,实现AB进程能够随时收发数据。
提示:用多进程或者多线程实现
程序:
A线程:
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/wait.h>
#include <fcntl.h>
#include <unistd.h>
#include <stdlib.h>
#include <errno.h>
#include <string.h>
int main(int argc, const char *argv[])
{
umask(0);
if(mkfifo("./myfifo",0664)<0)
{
printf("errno=%d\n",errno);
if(errno!=17)
{
perror("mkfifo");
return -1;
}
}
printf("create myfifo success\n");
//以只写的方式打开
int fd=open("./myfifo",O_WRONLY);
if(fd<0)
{
perror("open");
return -1;
}
printf("open myfifo successs\n");
//
if(mkfifo("./myfifo1",0664)<0)
{
printf("errno=%d\n",errno);
if(errno!=17)
{
perror("mkfifo1");
return -1;
}
}
printf("create myfifo1 success\n");
//以只写的方式打开
int fd1=open("./myfifo1",O_RDONLY);
if(fd1<0)
{
perror("open");
return -1;
}
printf("open myfifo1 successs\n");
char buf[128]="";
ssize_t res=0;
//创建一个子进程
pid_t pid=fork();
//向管道中写入数据
if(pid>0)
{
while(1)
{
bzero(buf,sizeof(buf));
fgets(buf,sizeof(buf),stdin);
buf[strlen(buf)-1]=0;
res=write(fd,buf,sizeof(buf));
if(strcmp(buf,"quit")==0)
{
break;
}
if(res<0)
{
perror("write");
return -1;
}
}
wait(NULL);
}
else if(pid==0)
{
while(1)
{
bzero(buf,sizeof(buf));
//读取管道myfifo1中的内容
res=read(fd1,buf,sizeof(buf));
if(res<0)
{
perror("read");
return -1;
}
else if(0==res)//写端均关闭
{
fprintf(stderr,"对方进程退出\n");
}
printf("B进程说的是:%s\n",buf);
if(strcmp(buf,"quit")==0)
{
exit(0);
}
}
}
close(fd);
close(fd1);
return 0;
}
B线程:
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <errno.h>
#include <string.h>
int main(int argc, const char *argv[])
{
umask(0);
if(mkfifo("./myfifo",0664)<0)
{
printf("errno=%d\n",errno);
if(errno!=17)
{
perror("mkfifo");
return -1;
}
}
printf("create myfifo success\n");
//以只写的方式打开
int fd=open("./myfifo",O_RDONLY);
if(fd<0)
{
perror("open");
return -1;
}
printf("open myfifo successs\n");
//
if(mkfifo("./myfifo1",0664)<0)
{
printf("errno=%d\n",errno);
if(errno!=17)
{
perror("mkfifo1");
return -1;
}
}
printf("create myfifo1 success\n");
//以只写的方式打开
int fd1=open("./myfifo1",O_WRONLY);
if(fd1<0)
{
perror("open");
return -1;
}
printf("open myfifo1 successs\n");
char buf[128]="";
ssize_t res=0;
//创建子进程
pid_t pid=fork();
//向管道中写入数据
while(1)
{
bzero(buf,sizeof(buf));
//读取管道myfifo1中的内容
res=read(fd,buf,sizeof(buf));
printf("A进程说的是:%s\n",buf);
if(res<0)
{
perror("read");
return -1;
}
else if(0==res)//写端均关闭
{
fprintf(stderr,"对方进程退出\n");
break;
}
while(1)
{
bzero(buf,sizeof(buf));
if(pid>0)
{
fgets(buf,sizeof(buf),stdin);
buf[strlen(buf)-1]=0;
res=write(fd1,buf,sizeof(buf));
if(res<0)
{
perror("write");
return -1;
}
}
else if(pid==0 && flag==1)
{
fgets(buf,sizeof(buf),stdin);
buf[strlen(buf)-1]=0;
res=write(fd1,buf,sizeof(buf));
if(res<0)
{
perror("write");
return -1;
}
}
}
}
close(fd);
close(fd1);
return 0;
}
运行效果: