您好,登錄后才能下訂單哦!
這篇文章給大家分享的是有關Linux進程通信之FIFO如何實現(xiàn)的內(nèi)容。小編覺得挺實用的,因此分享給大家做個參考,一起跟隨小編過來看看吧。
FIFO通信(first in first out)
FIFO 有名管道,實現(xiàn)無血緣關系進程通信。
創(chuàng)建一個管道的偽文件
a.mkfifo testfifo 命令創(chuàng)建
b.也可以使用函數(shù)int mkfifo(const char *pathname, mode_t mode);
內(nèi)核會針對fifo文件開辟一個緩沖區(qū),操作fifo文件,可以操作緩沖區(qū),實現(xiàn)進程間通信–實際上就是文件讀寫
man 3 mkfifo
#include <sys/types.h> #include <sys/stat.h> int mkfifo(const char *pathname, mode_t mode);
注意事項:
FIFOs
Opening the read or write end of a FIFO blocks until the other end is also opened (by another process or thread). See
fifo(7) for further details.
打開fifo文件時候,read端會阻塞等待write端open,write端同理,也會阻塞等待另外一段打開。
代碼示例:
file_w.c 寫端
#include <stdio.h> #include <stdlib.h> #include <sys/wait.h> #include <sys/types.h> #include <sys/stat.h> #include <unistd.h> #include <fcntl.h> #include <string.h> int main(int argc, char *argv[]) { if(argc != 2) { printf("./a.out filename1\n"); return -1; } printf("begin open w\n"); int o_ret = open(argv[1], O_WRONLY); printf("end open w\n"); char buf[256]; int num = 0; while (1) { memset(buf, '\0', sizeof(buf)); sprintf(buf, "xiaoming--%d", num++); printf("strlen(buf) = %d\n", strlen(buf)); write(o_ret, buf, strlen(buf)); sleep(1); } close(o_ret); return 0; }
file_r.c 讀端
#include <stdio.h> #include <stdlib.h> #include <sys/wait.h> #include <sys/types.h> #include <sys/stat.h> #include <unistd.h> #include <fcntl.h> #include <string.h> int main(int argc, char *argv[]) { if(argc != 2) { printf("./a.out filename1\n"); return -1; } printf("begin open r\n"); int o_ret = open(argv[1], O_RDONLY); printf("end open r\n"); char buf[256]; int num = 0; while (1) { memset(buf, '\0', sizeof(buf)); read(o_ret, buf, sizeof(buf)); printf("strlen(buf) = %d\n", strlen(buf)); printf("read is%s\n", buf); } close(o_ret); return 0; }
Linux是一種免費使用和自由傳播的類UNIX操作系統(tǒng),是一個基于POSIX的多用戶、多任務、支持多線程和多CPU的操作系統(tǒng),使用Linux能運行主要的Unix工具軟件、應用程序和網(wǎng)絡協(xié)議。
感謝各位的閱讀!關于“Linux進程通信之FIFO如何實現(xiàn)”這篇文章就分享到這里了,希望以上內(nèi)容可以對大家有一定的幫助,讓大家可以學到更多知識,如果覺得文章不錯,可以把它分享出去讓更多的人看到吧!
免責聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。