使用有名管道实现AB进程进行通话,做到时发时收
A进程代码:
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <errno.h>
#include <string.h>
#include <pthread.h>
#include <signal.h>
int fd_w;
int fd_r;
ssize_t res = 0;
char buf[128] = "";
int main(int argc, const char *argv[])
{
fd_w = open("./fifo", O_WRONLY);
fd_r = open("./fifo1", O_RDONLY);
//建立进程
pid_t cpid = fork();
//建立两个通道
if(mkfifo("./fifo1", 0775) < 0)
{
if(17 != errno)
{
perror("mkfifo");
return -1;
}
}
if(mkfifo("./fifo", 0775) < 0)
{
if(17 != errno)
{
perror("mkfifo");
return -1;
}
}
//主进程
if(cpid > 0)
{
while(1)
{
printf("请输入>>>>>");
bzero(buf, sizeof(buf));
fgets(buf, sizeof(buf), stdin);
buf[strlen(buf)-1] = 0;
if(strcmp(buf, "quit") == 0)
{
kill(cpid, 9);
break;
}
if(write(fd_w, buf, sizeof(buf)) < 0)
{
perror("write");
return -1;
}
printf("写入成功\n");
}
}
//子进程
else if(cpid == 0)
{
while(1)
{
res = read(fd_r, buf, sizeof(buf));
if(res < 0)
{
perror("read");
return -1;
}
else if(res == 0)
{
printf("对端进程退出\n");
break;
}
printf("res1 = %ld | buf = %s\n", res, buf);
}
}
else
{
perror("fork");
return -1;
}
//关闭文件
close(fd_w);
close(fd_r);
return 0;
}
B进程代码
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <errno.h>
#include <string.h>
#include <pthread.h>
#include <signal.h>
int fd_w, fd_r;
ssize_t res = 0;
char buf[128] = "";
int main(int argc, const char *argv[])
{
//建立进程
pid_t cpid = fork();
//建立两个管道
if(mkfifo("./fifo1", 0775) < 0)
{
if(17 != errno)
{
perror("mkfifo");
return -1;
}
}
if(mkfifo("./fifo", 0775) < 0)
{
if(17 != errno)
{
perror("mkfifo");
return -1;
}
}
//打开通道
fd_r = open("./fifo", O_RDONLY);
fd_w = open("./fifo1", O_WRONLY);
//主进程
if(cpid > 0)
{
while(1)
{
bzero(buf, sizeof(buf));
res = read(fd_r, buf, sizeof(buf));
if(res < 0)
{
perror("read");
return -1;
}
else if(res == 0)
{
printf("对端进程退出\n");
break;
}
printf("res = %ld | buf = %s\n", res, buf);
}
}
//子进程
else if(cpid == 0)
{
while(1)
{
printf("请回复>>>>>");
fgets(buf, sizeof(buf), stdin);
buf[strlen(buf) - 1] = 0;
if(strcmp(buf, "quit") == 0)
{
kill(cpid, 9);
break;
}
if(write(fd_w, buf, sizeof(buf)) < 0)
{
perror("write");
return -1;
}
printf("回复成功\n");
}
}
else
{
perror("fork");
return -1;
}
//关闭打开的文件
close(fd_w);
close(fd_r);
return 0;
}
程序A进程结果:
ubuntu@ubuntu:homwork$ ./h1.out
请输入>>>>>qwe
写入成功
请输入>>>>>qwe
写入成功
请输入>>>>>qwe
写入成功
请输入>>>>>res1 = 128 | buf = qwe
res1 = 128 | buf = qwe
res1 = 128 | buf = qwe
对端进程退出
程序B进程结果:
ubuntu@ubuntu:homwork$ ./h2.out
请回复>>>>>res = 128 | buf = qwe
res = 128 | buf = qwe
res = 128 | buf = qwe
qwe
回复成功
请回复>>>>>qwe
回复成功
请回复>>>>>qwe
回复成功
请回复>>>>>quit
已杀死