在计算技术中,一种命名管道(也称为 先进先出 )是进程间通信的方法之一。
null
- 它是Unix上传统管道概念的扩展。传统的管道是“未命名”的,其持续时间仅与流程相同。
- 然而,命名管道可以在系统运行期间持续,超过流程的生命周期。如果不再使用,可以将其删除。
- 通常,命名管道以文件的形式出现,通常进程会附加到该文件以进行进程间通信。FIFO文件是本地存储器上的一种特殊类型的文件,它允许两个或多个进程通过读取/写入该文件来相互通信。
- 一个FIFO特殊文件通过调用 mkfifo() 在C中,一旦我们以这种方式创建了FIFO特殊文件,任何进程都可以像普通文件一样打开它进行读写。然而,它必须在两端同时打开,然后才能继续对其执行任何输入或输出操作。
创建FIFO文件: 为了创建FIFO文件,使用函数调用,即mkfifo。
CPP
int mkfifo( const char *pathname, mode_t mode); |
mkfifo()生成一个名为 路径名 在这里 模式 指定FIFO的权限。它由进程的umask以通常的方式进行修改:所创建文件的权限为(mode&~umask)。 使用FIFO: 由于命名管道(FIFO)是一种文件,我们可以使用与之相关的所有系统调用,即。 打开 , 阅读 , 写 , 关 . 演示命名管道的示例程序: 有两个程序使用相同的FIFO。程序1先写,然后读。程序2先读,然后写。他们都一直这样做直到终止。
// C program to implement one side of FIFO// This side writes first, then reads#include <stdio.h>#include <string.h>#include <fcntl.h>#include <sys/stat.h>#include <sys/types.h>#include <unistd.h>int main(){ int fd; // FIFO file path char * myfifo = "/tmp/myfifo"; // Creating the named file(FIFO) // mkfifo(<pathname>, <permission>) mkfifo(myfifo, 0666); char arr1[80], arr2[80]; while (1) { // Open FIFO for write only fd = open(myfifo, O_WRONLY); // Take an input arr2ing from user. // 80 is maximum length fgets(arr2, 80, stdin); // Write the input arr2ing on FIFO // and close it write(fd, arr2, strlen(arr2)+1); close(fd); // Open FIFO for Read only fd = open(myfifo, O_RDONLY); // Read from FIFO read(fd, arr1, sizeof(arr1)); // Print the read message printf("User2: %s", arr1); close(fd); } return 0;}
// C program to implement one side of FIFO// This side reads first, then reads#include <stdio.h>#include <string.h>#include <fcntl.h>#include <sys/stat.h>#include <sys/types.h>#include <unistd.h>int main(){ int fd1; // FIFO file path char * myfifo = "/tmp/myfifo"; // Creating the named file(FIFO) // mkfifo(<pathname>,<permission>) mkfifo(myfifo, 0666); char str1[80], str2[80]; while (1) { // First open in read only and read fd1 = open(myfifo,O_RDONLY); read(fd1, str1, 80); // Print the read string and close printf("User1: %s", str1); close(fd1); // Now open in write mode and write // string taken from user. fd1 = open(myfifo,O_WRONLY); fgets(str2, 80, stdin); write(fd1, str2, strlen(str2)+1); close(fd1); } return 0;}
© 版权声明
文章版权归作者所有,未经允许请勿转载。
THE END