命名管道文件的使用
管道文件分为存在内存的无名管道和存在磁盘的有名管道,无名管道只能用于具有亲缘关系的进程之间,这就大大限制了管道的使用。而有名管道可以解决这个问题,他可以实现任意两个进程之间的通信。
有名管道的创建可以使用mkfifo函数,函数的使用类似于open函数的使用,可以指定管道的路径和打开的模式。
示例代码:
/*fifo_write.c*/#include <sys/types.h>#include <sys/stat.h>#include <errno.h>#include <fcntl.h>#include <stdio.h>#include <stdlib.h>#include <string.h>#define FIFO "/tmp/myfifo"/*定义管道文件的目录和文件名*/int main(int argc,char *argv[]){int fd;char buffer_write[100];int bytes_write;if( argc == 1){printf("Usage:%s string\n",argv[0]);exit(1);}/*以非阻塞的方式打开管道文件*/fd = open(FIFO,O_WRONLY | O_NONBLOCK);if( fd == -1 ){printf("Open error:no reading process!\n");exit(1);}strcpy(buffer_write,argv[1]);if( (bytes_write=write(fd,buffer_write,100)) == -1 ){if( errno == EAGAIN ){printf("The FIFO has not been read!\n\a");exit(1);}}elseprintf("Write %s to the FIFO!\n",buffer_write);return 0;}