要求:用多进程或者多线程实现
代码如下:
#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);
//创建fifo文件
if(mkfifo("./myfifo",0664)<0)
{
printf("errno = %d\n",errno);
if(errno != EEXIST)
{
perror("mkfifo");
return -1;
}
}
if(mkfifo("./myfifo1",0664)<0)
{
printf("errno = %d\n",errno);
if(errno != EEXIST)
{
perror("mkfifo");
return -1;
}
}
printf("有名管道创建成功__%d__\n",__LINE__);
int fd = open("./myfifo",O_RDONLY);
if(fd<0)
{
perror("open");
ssize_t res1=0;
return -1;
}
int fd2 = open("./myfifo1",O_WRONLY);
if(fd2<0)
{
perror("open");
return -1;
}
char buf[128] = "";
ssize_t res = 0;
//创建一个进程
pid_t pid =fork();
//父进程
if(pid>0)
{
while(1)
{
//向管道中写入数据
bzero(buf,sizeof(buf));
//printf("父亲发送>>>");
fgets(buf,sizeof(buf),stdin);
buf[strlen(buf)-1]=0;
res = write(fd2,buf,sizeof(buf));
if(res<0)
{
perror("write");
return -1;
}
if(strcmp(buf,"quit")==0)
{
break;
}
printf("父成功发送数据\n");
}
}
//子进程
else if(pid==0)
{
while(1)
{
//从管道中读取数据
bzero(buf,sizeof(buf));
res = read(fd,buf,sizeof(buf));
if(res<0)
{
perror("read");
return -1;
}
else if(res ==0)
{
fprintf(stderr,"对方进程退出\n");
break;
}
if(strcmp(buf,"quit")==0)
{
break;
}
printf("父亲接收到%s\n",buf);
}
}
else if(pid<0)
{
perror("fork");
return -1;
}
close(fd);
close(fd2);
return 0;
}
#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);
//创建fifo文件
if(mkfifo("./myfifo",0664)<0)
{
printf("errno = %d\n",errno);
if(errno != EEXIST)
{
perror("mkfifo");
return -1;
}
}
if(mkfifo("./myfifo1",0664)<0)
{
printf("errno = %d\n",errno);
if(errno != EEXIST)
{
perror("mkfifo");
return -1;
}
}
printf("有名管道创建成功\n");
int fd = open("./myfifo",O_WRONLY);
if(fd<0)
{
perror("open");
return -1;
}
int fd2 = open("./myfifo1",O_RDONLY);
if(fd2<0)
{
perror("open");
ssize_t res1=0;
return -1;
}
char buf[128] = "";
ssize_t res = 0;
//创建一个进程
pid_t pid =fork();
//父进程
if(pid>0)
{
while(1)
{ //从管道中读取数据
bzero(buf,sizeof(buf));
res = read(fd2,buf,sizeof(buf));
if(res<0)
{
perror("read");
return -1;
}
else if(res ==0)
{
fprintf(stderr,"对方进程退出\n");
break;
}
if(strcmp(buf,"quit")==0)
{
break;
}
printf("儿子接收到%s\n",buf);
}
}
//子进程
else if(pid==0)
{
while(1)
{
//向管道中写入数据
bzero(buf,sizeof(buf));
//printf("父亲发送>>>");
fgets(buf,sizeof(buf),stdin);
buf[strlen(buf)-1]=0;
res = write(fd,buf,sizeof(buf));
if(res<0)
{
perror("write");
return -1;
}
if(strcmp(buf,"quit")==0)
{
break;
}
printf("儿子成功发送数据\n");
}
}
else if(pid<0)
{
perror("fork");
return -1;
}
close(fd);
sleep(1);
close(fd2);
return 0;
}
结果如下: