日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當(dāng)前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

FIFO(命名管道)

發(fā)布時間:2023/11/30 编程问答 26 豆豆
生活随笔 收集整理的這篇文章主要介紹了 FIFO(命名管道) 小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.

FIFO常被稱為命名管道,以區(qū)分管道(pipe)。管道(pipe)只能用于“有血緣關(guān)系”的進(jìn)程間。但通過FIFO,不相關(guān)的進(jìn)程也能交換數(shù)據(jù)。FIFO是Linux基礎(chǔ)文件類型中的一種(p,管道文件)。但FIFO文件在磁盤上沒有數(shù)據(jù)塊,僅僅用來標(biāo)識內(nèi)核中一條通道。各進(jìn)程可以打開這個文件進(jìn)行read/write,實(shí)際上是在讀寫內(nèi)核通道,這樣就實(shí)現(xiàn)了進(jìn)程間通信。另外,使用統(tǒng)一fifo文件,可以有多個讀端和多個寫端。

FIFO文件(p)的創(chuàng)建方式:1. 命令:mkfifo 管道名;? 2. 庫函數(shù):int mkfifo(const char *pathname, ?mode_t mode);? 成功:0; 失敗:-1??? 當(dāng)mkfifo的第一個參數(shù)是一個已經(jīng)存在的路徑名時,則會出錯返回-1,因此一般使用該函數(shù)時要判斷返回值。 第二個參數(shù)為8進(jìn)制數(shù),一般設(shè)置為0666即可,即管道文件只需要讀寫權(quán)限,不需要執(zhí)行權(quán)限。? ??包含庫文件:#include <sys/types.h>??? #include <sys/stat.h>

一旦創(chuàng)建了一個FIFO,就可以使用open打開它,常見的文件I/O函數(shù)都可用于fifo。如:close、read、write、unlink等。unlink可以刪除一個管道文件。

注意:當(dāng)進(jìn)程對命名管道的使用結(jié)束后,命名管道依然存在于文件系統(tǒng)中,除非對其進(jìn)行刪除操作。命名管道的數(shù)據(jù)讀取后也會消失(不能反復(fù)讀取),即且嚴(yán)格遵循先進(jìn)先出的規(guī)則。因此,每次命名管道文件使用完后,其大小為0字節(jié),不會產(chǎn)生中間臨時文件。

?

//使用函數(shù)創(chuàng)建命名管道(命令行參數(shù)指定文件名字)

#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); }

//向管道文件中讀寫數(shù)據(jù),實(shí)現(xiàn)進(jìn)程間通信

#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); //多個讀端時應(yīng)增加睡眠秒數(shù),放大效果}close(fd);return 0; }

?

總結(jié)

以上是生活随笔為你收集整理的FIFO(命名管道)的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網(wǎng)站內(nèi)容還不錯,歡迎將生活随笔推薦給好友。