Linux 進程通信之FIFO的實現(xiàn)
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);
- 內核會針對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 KVM的QCOW2 和 ROW的詳解及區(qū)別介紹
這篇文章主要介紹了Linux QCOW2 和 ROW的詳解及區(qū)別介紹的相關資料,需要的朋友可以參考下2016-11-11
CentOS 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-01
Ubuntu報“無法解析域名cn.archive.ubuntu.com“問題解決辦法
在Ubuntu系統(tǒng)上使用sudo?apt?update命令更新時可能遇到“無法解析域名cn.archive.ubuntu.com”的問題,這通常是因為cn.archive.ubuntu.com的鏡像資源不穩(wěn)定,為解決此問題,可以更換為穩(wěn)定性好、速度快的鏡像源,需要的朋友可以參考下2024-11-11
在Linux操作系統(tǒng)中修改環(huán)境變量的方法
在Linux操作系統(tǒng)中,有時候跟著教程安裝了一些軟件,安裝成功后,很高興的準備運行該軟件相應命令,但是偶爾會遇到”Command not found…“的提示。原因是因為你安裝的軟件需要設置環(huán)境變量才能運行。接下來跟著小編一起學習在Linux操作系統(tǒng)中修改環(huán)境變量的方法。2015-08-08
Apache NameVirtualHost *:80 has no VirtualHosts問題解決辦法
這篇文章主要介紹了Apache NameVirtualHost *:80 has no VirtualHosts問題解決辦法,一個很簡單的配置性錯誤,需要的朋友可以參考下2014-08-08

