1> 使用有名管道实现两个进程之间相互通信,提示:可以使用多线程或多进程实现
代码:
1.c
#include <head.h>
int main(int argc, const char *argv[])
{
pid_t pid = fork();
int wfd = open("./myfifo1",O_WRONLY);
int rfd = open("./myfifo2",O_RDONLY);
if(wfd == -1)
{
perror("open");
return -1;
}
else if(pid == 0)
{
char buf[128] = "";
while(1)
{
bzero(buf,sizeof(buf));
printf("进程1请输入:");
fgets(buf,sizeof(buf),stdin);
buf[strlen(buf)-1] = '\0';
write(wfd,buf,sizeof(buf));
if(strcmp(buf,"quit") == 0)
{
printf("写进程1退出\n");
break;
}
}
}
else
{
if(rfd == -1)
{
perror("open");
return -1;
}
char buf[128] = "";
while(1)
{
bzero(buf,sizeof(buf));
read(rfd,buf,sizeof(buf));
if(strcmp(buf,"quit") == 0)
{
printf("读进程1退出\n");
break;
}
printf("\n");
printf("进程1读取的数据:%s\n",buf);
printf("进程1请输入:");
}
}
close(rfd);
close(wfd);
return 0;
}
2.c
#include <head.h>
int main(int argc, const char *argv[])
{
pid_t pid = fork();
int rfd = open("./myfifo1",O_RDONLY);
int wfd = open("./myfifo2",O_WRONLY);
if(pid < 0)
{
perror("pid");
return -1;
}
else if(pid == 0)
{
if(rfd == -1)
{
perror("open");
return -1;
}
char buf[128] = "";
while(1)
{
bzero(buf,sizeof(buf));
read(rfd,buf,sizeof(buf));
if(strcmp(buf,"quit") == 0)
{
printf("读进程2退出\n");
break;
}
printf("\n");
printf("进程2读取的数据:%s\n",buf);
printf("进程2请输入:");
}
}
else
{
char buf[128] = "";
while(1)
{
bzero(buf,sizeof(buf));
printf("进程2请输入:");
fgets(buf,sizeof(buf),stdin);
buf[strlen(buf)-1] = '\0';
write(wfd,buf,sizeof(buf));
if(strcmp(buf,"quit") == 0)
{
printf("写进程2退出\n");
break;
}
}
}
close(rfd);
close(wfd);
return 0;
}
create.c
#include <head.h>
int main(int argc, const char *argv[])
{
if(mkfifo("./myfifo1",0664) != 0)
{
perror("myfifo");
return -1;
}
if(mkfifo("./myfifo2",0664) != 0)
{
perror("myfifo");
return -1;
}
while(1)
{}
return 0;
}
运行结果:
2> 思维导图