FIFO常被稱為命名管道,以區分管道(pipe)。管道(pipe)只能用于“有血緣關系”的進程間。但通過FIFO,不相關的進程也能交換數據。FIFO是Linux基礎文件類型中的一種(p,管道文件)。但FIFO文件在磁盤上沒有數據塊,僅僅用來標識內核中一條通道。各進程可以打開這個文件進行read/write,實際上是在讀寫內核通道,這樣就實現了進程間通信。另外,使用統一fifo文件,可以有多個讀端和多個寫端。
FIFO文件(p)的創建方式:1. 命令:mkfifo 管道名;? 2. 庫函數:int mkfifo(const char *pathname, ?mode_t mode);? 成功:0; 失敗:-1??? 當mkfifo的第一個參數是一個已經存在的路徑名時,則會出錯返回-1,因此一般使用該函數時要判斷返回值。 第二個參數為8進制數,一般設置為0666即可,即管道文件只需要讀寫權限,不需要執行權限。? ??包含庫文件:#include <sys/types.h>??? #include <sys/stat.h>
一旦創建了一個FIFO,就可以使用open打開它,常見的文件I/O函數都可用于fifo。如:close、read、write、unlink等。unlink可以刪除一個管道文件。
注意:當進程對命名管道的使用結束后,命名管道依然存在于文件系統中,除非對其進行刪除操作。命名管道的數據讀取后也會消失(不能反復讀取),即且嚴格遵循先進先出的規則。因此,每次命名管道文件使用完后,其大小為0字節,不會產生中間臨時文件。
?
//使用函數創建命名管道(命令行參數指定文件名字)
#include <sys/types.h>
#include <sys/stat.h>
#include <stdio.h>
#include <stdlib.h>int main(int argc , char *argv[ ])
{if(argc < 2){printf("./a.out fifoname\n");exit(1);}int ret;mode_t mode=0666;ret = mkfifo(argv[1],mode);if(ret == -1){perror("mkfifo");exit(1);}exit(0);
}
//向管道文件中讀寫數據,實現進程間通信
#include <stdio.h>
#include <unistd.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <fcntl.h>
#include <stdlib.h>
#include <string.h>void sys_err(char *str)
{perror(str);exit(1);
}int main(int argc, char *argv[])
{int fd, i;char buf[4096];if (argc < 2) {printf("Enter like this: ./a.out fifoname\n");return -1;}fd = open(argv[1], O_WRONLY);if (fd < 0)sys_err("open");i = 0;while (1) {sprintf(buf, "hello itcast %d\n", i++);write(fd, buf, strlen(buf));sleep(1);}close(fd); return 0;
}#include <stdio.h>
#include <unistd.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <fcntl.h>
#include <stdlib.h>
#include <string.h>void sys_err(char *str)
{perror(str);exit(1);
}int main(int argc, char *argv[])
{int fd, len;char buf[4096];if (argc < 2) {printf("./a.out fifoname\n");return -1;}fd = open(argv[1], O_RDONLY);if (fd < 0)sys_err("open");while (1) {len = read(fd, buf, sizeof(buf));write(STDOUT_FILENO, buf, len);sleep(3); //多個讀端時應增加睡眠秒數,放大效果}close(fd);return 0;
}
?