Linux 進(jìn)程通信之FIFO的實(shí)現(xiàn)
FIFO通信(first in first out)
FIFO 有名管道,實(shí)現(xiàn)無(wú)血緣關(guān)系進(jìn)程通信。
- 創(chuàng)建一個(gè)管道的偽文件
- a.mkfifo testfifo 命令創(chuàng)建
- b.也可以使用函數(shù)int mkfifo(const char *pathname, mode_t mode);
- 內(nèi)核會(huì)針對(duì)fifo文件開(kāi)辟一個(gè)緩沖區(qū),操作fifo文件,可以操作緩沖區(qū),實(shí)現(xiàn)進(jìn)程間通信–實(shí)際上就是文件讀寫(xiě)
man 3 mkfifo
#include <sys/types.h> #include <sys/stat.h> int mkfifo(const char *pathname, mode_t mode);
注意事項(xiàng):
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.
打開(kāi)fifo文件時(shí)候,read端會(huì)阻塞等待write端open,write端同理,也會(huì)阻塞等待另外一段打開(kāi)。
代碼示例:
file_w.c 寫(xiě)端
#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; }
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
Linux KVM的QCOW2 和 ROW的詳解及區(qū)別介紹
這篇文章主要介紹了Linux QCOW2 和 ROW的詳解及區(qū)別介紹的相關(guān)資料,需要的朋友可以參考下2016-11-11CentOS 7.x編譯安裝Nginx1.10.3+MySQL5.7.16+PHP5.2 5.3 5.4 5.5 5.6
這篇文章主要介紹了CentOS 7.x編譯安裝Nginx1.10.3+MySQL5.7.16+PHP5.2 5.3 5.4 5.5 5.6 7.0 7.1多版本全能環(huán)境,需要的朋友可以參考下2018-01-01Ubuntu報(bào)“無(wú)法解析域名cn.archive.ubuntu.com“問(wèn)題解決辦法
在Ubuntu系統(tǒng)上使用sudo?apt?update命令更新時(shí)可能遇到“無(wú)法解析域名cn.archive.ubuntu.com”的問(wèn)題,這通常是因?yàn)閏n.archive.ubuntu.com的鏡像資源不穩(wěn)定,為解決此問(wèn)題,可以更換為穩(wěn)定性好、速度快的鏡像源,需要的朋友可以參考下2024-11-11在Linux操作系統(tǒng)中修改環(huán)境變量的方法
在Linux操作系統(tǒng)中,有時(shí)候跟著教程安裝了一些軟件,安裝成功后,很高興的準(zhǔn)備運(yùn)行該軟件相應(yīng)命令,但是偶爾會(huì)遇到”Command not found…“的提示。原因是因?yàn)槟惆惭b的軟件需要設(shè)置環(huán)境變量才能運(yùn)行。接下來(lái)跟著小編一起學(xué)習(xí)在Linux操作系統(tǒng)中修改環(huán)境變量的方法。2015-08-08Apache NameVirtualHost *:80 has no VirtualHosts問(wèn)題解決辦法
這篇文章主要介紹了Apache NameVirtualHost *:80 has no VirtualHosts問(wèn)題解決辦法,一個(gè)很簡(jiǎn)單的配置性錯(cuò)誤,需要的朋友可以參考下2014-08-08