代码:
client.c
#include <stdio.h>
#include <fcntl.h>
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#define __PATH__ "/home/chen/7Month/7_28/FIFO/my_fifo"//这个就是管道的名字,和建立的路径
int main()
{
int fd = open(__PATH__,O_WRONLY,0);//以只写的方式打开
if(fd < 0){
perror("error");
return 2;
}
char buf[1024];
while(1){
printf("client Enter :");
fflush(stdout);
memset(buf,'\0',sizeof(buf));
fgets(buf,sizeof(buf)-1,stdin);
buf[strlen(buf)-1] = '\0';
write(fd,buf,strlen(buf));
if(strcasecmp(buf,"Quit") == 0){//忽略大小写
break;
}
}
close(fd);
printf("client Quit\n");
return 0;
}
server.c:
#include <stdio.h>
#include <fcntl.h>
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#define __PATH__ "/home/chen/7Month/7_28/FIFO/my_fifo"
int main()
{
if(mkfifo(__PATH__,0666|S_IFIFO) < 0){
perror("error");
return 1;
}
int fd = open(__PATH__,O_RDONLY,0);//以只读的方式打开命名管道
printf("open file success\n");
if(fd < 0){
perror("error");
}
char buf[1024];
while(1){
memset(buf,'\0',sizeof(buf));
int len = read(fd,buf,sizeof(buf)-1);
if(len > 0){
printf("client say : %s\n",buf);
}
if(strcasecmp("Quit",buf) == 0){//忽略大小写的quit
break;
}
}
close(fd);
printf("server Quit\n");
return 0;
}
运行结果:
client.c
server.c
分析:
管道其实就是个文件,生命周期是和普通的文件是一样的,不删除它永远存在