- 有名管道:
-
區(qū)別于
無名管道,其可以用于任意進程間的通信
; - 同無名管道一樣,也是
半雙工的通信方式
; - 有名管道的大小也是
64KB
; - 也是
不能使用lseek函數(shù)
; - 其本質上,是在內存上,在文件系統(tǒng)上
只是一個標識
; - 有名管道會創(chuàng)建一個管道文件,只需要打開這個文件,進行相應的讀寫操作即可;
- 讀寫特點:
- 若讀端
存在
寫管道,那么有多少數(shù)據(jù),就寫多少數(shù)據(jù),直到有名管道寫滿
為止,此時會出現(xiàn)寫阻塞
; - 若讀端
不存在
寫管道,會出現(xiàn)兩種情況
; - 第一種:
讀端
沒有打開,寫端
在open函數(shù)
的位置阻塞; - 第二種:
讀端
打開后關閉,會出現(xiàn)管道破裂
的現(xiàn)象; - 若寫端
存在
讀管道,那么有多少數(shù)據(jù),就讀多少數(shù)據(jù),沒有數(shù)據(jù)的時候,會出現(xiàn)阻塞等待
; - 若寫端
不存在
讀管道,也會出現(xiàn)兩種情況
; - 第一種:
寫端
沒有打開,讀端
在open函數(shù)
的位置阻塞; - 第二種:
寫端
打開后關閉,有多少數(shù)據(jù),就讀多少,沒有數(shù)據(jù)的時候,就會立即返回,即非阻塞的狀態(tài)
; - 創(chuàng)建有名管道(mkfifo函數(shù)):
#include <sys/types.h>
#include <sys/stat.h>
int mkfifo(const char *pathname, mode_t mode);
/*
功能:
創(chuàng)建管道文件
參數(shù):
pathname:管道路徑和名字
mode:管道文件的權限
返回值:
成功 0
失敗 -1 重置錯誤碼
*/
- 示例代碼:
- 寫端:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <sys/wait.h>
#include <stdbool.h>
int main(int argc, char const *argv[])
{
int fd = open("./fifo_k",O_WRONLY);
if(-1 == fd)
{
perror("open error");
exit(-1);
}
char buf[128] = {0};
while(true)
{
memset(buf,0,sizeof(buf));
fgets(buf,sizeof(buf),stdin);
buf[strlen(buf) - 1] = '\0';
write(fd,buf,sizeof(buf));
if(!strncmp(buf,"quit",4))
{
exit(-1);
}
}
close(fd);
return 0;
}
- 讀端:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <sys/wait.h>
#include <stdbool.h>
int main(int argc, char const *argv[])
{
int fd = open("./fifo_k",O_RDONLY);
if(-1 == fd)
{
perror("open error");
exit(-1);
}
char buf[128] = {0};
while(true)
{
memset(buf,0,sizeof(buf));
read(fd,buf,sizeof(buf));
if(!strncmp(buf,"quit",4))
{
exit(-1);
}
printf("寫端發(fā)來的數(shù)據(jù)[%s]\n",buf);
}
close(fd);
return 0;
}
- 運行結果:
- 寫端:
hello
china
quit
- 讀端:
寫端發(fā)來的數(shù)據(jù)[hello]
寫端發(fā)來的數(shù)據(jù)[china]
文章來源地址http://www.zghlxwxcb.cn/news/detail-734143.html
文章來源:http://www.zghlxwxcb.cn/news/detail-734143.html
到了這里,關于多進程間通信學習之有名管道的文章就介紹完了。如果您還想了解更多內容,請在右上角搜索TOY模板網以前的文章或繼續(xù)瀏覽下面的相關文章,希望大家以后多多支持TOY模板網!