管道随进程 命名管道是一个设备文件,是存在于硬盘上的文件 用mkfifo()创建命名管道,可用于任何两个进程之间的通信 client.c(写端) #include<stdio.h> #include<stdlib.h> #include<sys/types.h> #include<sys/stat.h> #include<unistd.h> #include<string.h> #include<fcntl.h> #define _PATH_ "/tmp/file.tmp" #define _SIZE_ 100 int main() { int ret=mkfifo(_PATH_,0666|S_IFIFO); //create FIFO if(ret==-1) { perror("mkfifo"); return 1; } int fd=open(_PATH_,O_WRONLY); //open by the way of write if(fd<0) { printf("open error\n"); } char buf[_SIZE_]; memset(buf,‘\0‘,strlen(buf)+1); while(1) { scanf("%s",buf); int ret=write(fd,buf,strlen(buf)+1); if(ret<0) { printf("write error!\n"); break; } if(strncmp(buf,"quit",4)==0) { break; } } close(fd); return 0; } server.c(读端) #include<stdio.h> #include<sys/types.h> #include<sys/stat.h> #include<unistd.h> #include<fcntl.h> #include<string.h> #define _PATH_ "/tmp/file.tmp" #define _SIZE_ 100 int main() { int fd=open(_PATH_,O_RDONLY); if(fd<0) { printf("open file error\n"); return 1; } char buf[_SIZE_]; memset(buf,‘\0‘,sizeof(buf)); while(1) { int ret=read(fd,buf,sizeof(buf)); if(ret<=0) //error or read the end of file { printf("error or read the end of file\n"); break; } printf("%s\n",buf); if(strncmp(buf,"quit",4)==0) { break; } } close(fd); return 0; } 结果:
时间: 2024-10-19 20:57:37