1、两个进程间的通信
进程A
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <errno.h>
#include <fcntl.h>
#include <unistd.h>
#include <string.h>
int main(int argc, const char *argv[])
{
//创建两个管道文件
if(mkfifo("./FIFO1",0775) == -1)
{
if(errno != 17) //排除文件已经存在的错误
{
perror("mkfifo");
return -1;
}
}
if(mkfifo("./FIFO2",0775) == -1)
{
if(errno !=17)
{
perror("mkfifo");
return -1;
}
}
//以写的方式打开管道1
int fp_w = open("./FIFO1",O_WRONLY);
//以读的方式打开管道2
int fp_r = open("./FIFO2",O_RDONLY);
printf("create FIFO on success\n");
char buf[128]="";
while(1)
{
//写入
printf("A:");
fgets(buf,sizeof(buf),stdin);
buf[strlen(buf)-1] = '\0'; //确保是字符串
write(fp_w,buf,sizeof(buf));
if(strcmp(buf,"quit")==0)
{
printf("A已退出聊天\n");
close(fp_w);
close(fp_r);
return -1;
}
//读端
bzero(buf,sizeof(buf));//防止上次字符串干扰
if(read(fp_r,buf,sizeof(buf)) == -1)
{
perror("read");
return -1;
}
printf("B:");
printf("%s\n",buf);
if(strlen(buf) == 0)
{
printf("对方处于离线状态\n");
close(fp_w);
close(fp_r);
return -1;
}
if(strcmp(buf,"quit") == 0)
{
printf("对方已退出聊天\n");
close(fp_w);
close(fp_r);
return -1;
}
}
进程B
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <errno.h>
#include <fcntl.h>
#include <unistd.h>
#include <string.h>
int main(int argc, const char *argv[])
{
//创建两个管道文件
if(mkfifo("./FIFO1",0775) == -1)
{
if(errno != 17) //排除文件已经存在的错误
{
perror("mkfifo");
return -1;
}
}
if(mkfifo("./FIFO2",0775) == -1)
{
if(errno !=17)
{
perror("mkfifo");
return -1;
}
}
//以读的方式打开管道1
int fp_r = open("./FIFO1",O_RDONLY);
//以写的方式打开管道2
int fp_w = open("./FIFO2",O_WRONLY);
printf("create FIFO on success\n");
char buf[128]="";
while(1)
{
//读端
bzero(buf,sizeof(buf));//防止上次字符串干扰
if(read(fp_r,buf,sizeof(buf)) == -1)
{
perror("read");
return -1;
}
printf("A:");
printf("%s\n",buf);
if(strlen(buf) == 0)
{
printf("对方处于离线状态\n");
close(fp_w);
close(fp_r);
return -1;
}
if(strcmp(buf,"quit") == 0)
{
printf("对方已退出聊天\n");
close(fp_w);
close(fp_r);
return -1;
}
//写
printf("A:");
fgets(buf,sizeof(buf),stdin);
buf[strlen(buf)-1] = '\0'; //确保是字符串
write(fp_w,buf,sizeof(buf));
if(strcmp(buf,"quit")==0)
{
printf("A已退出聊天\n");
close(fp_w);
close(fp_r);
return -1;
}
}