1.核心理論:
有名管道:有名管道又稱FIFO文件,因此我們對有名管道的操作可以採用操作文件的方法,如使用open 、read 、write等函數。
fifo文件與普通文件的對比
FIFO文件 | 普通文件 |
---|---|
讀取FIFO文件的進程只能以“RDONLY“方式打開fifo文件 | 任意方式 |
寫FIFO 文件的進程只能以“WRONLY”方式打開fifo文件 | 任意方式 |
fifo文件讀取後就消失了管道文件的特點 | 普通文件內容被讀取後,還存在 |
2.函數學習
創建有名管道函數
函數原型:int mkfifo(const char *pathname , mode_t mode)
頭文件:sys/types.h sys/stat.h
功能:創建一個fifo文件
返回值:成功返回0,失敗返回 -1
參數:pathname:要創建的文件名(含路徑),mode:表明這個文件的訪問權限刪除有名管道文件
函數原型:int unlink(const char *pathname ,)
頭文件:unistd.h
功能:刪除一個文件名
返回值:成功返回0,失敗返回-1或者errno
參數:pathname: 要刪除的文件名(含路徑)
3.有名管道編程
- 寫進程程序
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>
#include <fcntl.h>
#include <stdio.h>
void main()
{
int fd;
char c_buf[11];
mkfifo("/home/shunzhi/apply/lesson14/test",0766);
fd = open("/home/shunzhi/apply/lesson14/test",O_WRONLY);
if(fd<0)
printf("mkfifo the file fail!\n");
write(fd,"hello world",12);
close(fd);
unlink("/home/shunzhi/apply/lesson14/test");
}
- 讀進程程序
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>
#include <fcntl.h>
#include <stdio.h>
void main()
{
int fd;
char c_buf[11];
mkfifo("/home/shunzhi/apply/lesson14/test",0666);
fd = open("/home/shunzhi/apply/lesson14/test",O_RDONLY);
read(fd,c_buf,12);
printf("printf fifofile : %s\n",c_buf);
close(fd);
unlink("/home/shunzhi/apply/lesson14/test");
}
注意:
- 對於進程間的有名管道通信的理解
首先,兩個進程必須同時運行,這樣管道才被建立起來,才能通信。
其次,通訊結束後,兩個進程纔會結束,也就是管道斷開;若通訊未完成,則進程兩個進程始終處於等待狀態。
譬如讀寫有名管道管道:先運行寫fifo文件,然後讀取fifo文件,讀取完成後,兩個進程同時結束;如果其中一方未完成則兩個進程始終處於等待狀態。
4.有名管道和無名管道的對比
無名管道只能用於父進程和子進程之間的通信,有名管道可以用於任意兩個進程之間的通信。