linux 用命名管道實現程序間通訊
阿新 • • 發佈:2018-12-09
什麼是命名管道
命名管道和匿名管道一樣適用於程序之間的通訊linux匿名管道詳解,但是使用範圍不同,匿名管道要求必須是親緣程序,而命名管道卻沒有這個限制,它可以用於同一臺機器主機上的任意程序間通訊。
命名管道的建立 ,使用
- 命令建立 :可以通過命令列命令建立
通過
mkfifo pipe_filename
- 程式碼建立:可以在函式裡通過引用庫函式建立 通過
#include <sys/types.h>
#include <sys/stat.h>
int mkfifo(const char *pathname, mode_t mode);
//第一個引數,是命名管道的檔名字,
//第二個引數,是要建立的這個檔案的檔案許可權,我們為了我們給出的許可權值,就是最終的許可權,可以在之前修改一下檔案建立掩碼。
//返回值:成功返回0,失敗返回<0的值,這裡還定義很多errno的巨集作為返回值,為了幫助我們判斷失敗原因。例如:
//EEXIST 檔案已經存在了,所以建立失敗pathname already exists.
3.命名管道的使用,就是當作檔案使用的。關於檔案的open,write,read,close詳細見部落格檔案io操作。 通過一個程式,完成寫,一個程式完成讀。兩個程式在兩個程序下跑,來驗證命名管道的使用方式。
//這個myfifo_r.c 是為了從命名管道中讀取資料
#include<stdio.h>
#include<unistd.h>
#include<stdlib.h>
#include<errno.h>
#include<string.h>
#include<fcntl.h>
//fcntl.h 是為了open,close等操作
int main
{
umask(0);
//建立命名管道
if(mkfifo("./mytest.fifo",0664) < 0)
{
if(errno == EEXIST)
{//檔案已存在無需再次建立}
else
{
perror("mkfifo error");
return -1;
}
}
//以只讀方式開啟O_RDONLY代表只讀許可權,類似見上文部落格連結
int fd = open("./mytest.fifo",O_RDONLY);
if(fd < 0)
{
perror("open fifo error");
return -1;
}
printf("mytest.fifo is open ,new you can read\n");
while(1)
{
char buff[1024] = {0};
int ret = read(fd,buff,1023);
//ret=0代表沒有讀到東西,
if(ret > 0)
{
printf("read:[%s]\n",buff);
}
else if(ret == 0)
{
printf("all write is close !!\n");
sleep(1);
}
}
close(fd);
return 0;
}
//這個myfifo_w.c 是為了向命名管道中寫入資料
#include<stdio.h>
#include<unistd.h>
#include<stdlib.h>
#include<errno.h>
#include<string.h>
#include<fcntl.h>
//fcntl.h 是為了open,close等操作
int main
{
umask(0);
//建立命名管道
if(mkfifo("./mytest.fifo",0664) < 0)
{
if(errno == EEXIST)
{//檔案已存在無需再次建立}
else
{
perror("mkfifo error");
return -1;
}
}
//以只讀方式開啟O_RDONLY代表只讀許可權,類似見上文部落格連結
int fd = open("./mytest.fifo",O_WRONLY);
if(fd < 0)
{
perror("open fifo error");
return -1;
}
printf("mytest.fifo is open ,new you can write\n");
while(1)
{
char buff[1024] = {0};
scanf("%s",buff);
write(fd,buff,strlen(buff)+1);
}
close(fd);
return 0;
}
執行結果:
命名管道特點
1. 如果以只讀read方式開啟open命名管道,則阻塞式等待直到都其他程序以只寫write的方式開啟命名管道。 如果以只寫write方式開啟open命名管道,則阻塞式等待直到都其他程序以只讀read的方式開啟命名管道。 2.如果這個命名管道是以讀寫的方式開啟,則不會阻塞式等待。 3.管道的生命週期隨程序,程序結束,管道關閉 4.管道自帶同步與互斥 5.和匿名管道不同,匿名管道建立後返回一個檔案描述符給我們使用。 而命名關係需要我們使用者自己開啟關閉檔案。