1.要求实现AB进程对话
要求随时收发,输入quit结束会话
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <string.h>
#include <errno.h>
#include <unistd.h>
#include <signal.h>
char buf[128]="";
int main(int argc, const char *argv[])
{
//创建管道文件
if(mkfifo("./fifo_01",0775) < 0)
{
if(17 != errno)
{
perror("mkfifo");
return -1;
}
}
printf("fifo_01 make success\n");
if(mkfifo("./fifo_02",0775) < 0)
{
if(17 != errno)
{
perror("mkfifo");
return -1;
}
}
printf("fifo_02 make success\n");
//打开文件
int fd_r = open("./fifo_01",O_RDONLY);
int fd_w = open("./fifo_02",O_WRONLY);
if(fd_r < 0 || fd_w < 0)
{
perror("open");
return -1;
}
printf("fifo_01 and fifo_02 open success\n");
//创建子进程
pid_t cpid = fork();
ssize_t res=0;
if(cpid > 0)//父进程写入管道文件
{
while(1)
{
printf("请输入>>>>>");
bzero(buf,sizeof(buf));
fgets(buf,sizeof(buf),stdin);
buf[strlen(buf)-1]=0;
if(write(fd_w,buf,sizeof(buf)) < 0)
{
perror("write");
return -1;
}
printf("输入成功\n");
//退出条件
if(strcmp(buf,"quit") == 0)
{
kill(cpid,9);
break;
}
}
}
else if(0 == cpid)
{
while(1)
{
res = read(fd_r,buf,sizeof(buf));
if(res < 0)
{
perror("read");
return -1;
}
else if(0 == res)
{
printf("对端进程退出");
break;
}
printf("res=%ld\tbuf=%s\n",res,buf);
}
}
//关闭文件
close(fd_r);
close(fd_w);
return 0;
}
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <string.h>
#include <errno.h>
#include <unistd.h>
#include <signal.h>
char buf[128]="";
ssize_t res;
int main(int argc, const char *argv[])
{
//创建管道文件
if(mkfifo("./fifo_01",0775) < 0)
{
if(17 != errno)
{
perror("mkfifo");
return -1;
}
}
printf("fifo_01 make success\n");
if(mkfifo("./fifo_02",0775) < 0)
{
if(17 != errno)
{
perror("mkfifo");
return -1;
}
}
printf("fifo_02 make success\n");
//打开文件
int fd_r = open("./fifo_02",O_RDONLY);
int fd_w = open("./fifo_01",O_WRONLY);
if(fd_r < 0 || fd_w < 0)
{
perror("open");
return -1;
}
printf("fifo_01 and fifo_02 open success\n");
//创建子进程
pid_t cpid = fork();
ssize_t res=0;
if(cpid > 0)//父进程写入管道文件
{
while(1)
{
printf("请输入>>>>>");
bzero(buf,sizeof(buf));
fgets(buf,sizeof(buf),stdin);
buf[strlen(buf)-1]=0;
if(write(fd_w,buf,sizeof(buf)) < 0)
{
perror("write");
return -1;
}
printf("输入成功\n");
//退出条件
if(strcmp(buf,"quit") == 0)
{
kill(cpid,9);
break;
}
}
}
else if(0 == cpid)
{
while(1)
{
bzero(buf,sizeof(buf));
res = read(fd_r,buf,sizeof(buf));
if(res < 0)
{
perror("read");
return -1;
}
else if(0 == res)
{
printf("对端进程退出");
break;
}
printf("res=%ld\tbuf=%s\n",res,buf);
}
}
//关闭文件
close(fd_r);
close(fd_w);
return 0;
}