程序是乙個獨立的資源管理單元,不同程序間的資源是獨立的,不能在乙個程序中訪問另乙個程序的使用者空間和記憶體空間。但是,程序不是孤立的,不同程序之間需要資訊的互動和狀態的傳遞,因此需要程序間資料的傳遞、同步和非同步的機制。
當然,這些機制不能由哪乙個程序進行直接管理,只能由作業系統來完成其管理和維護,linux提供了大量的程序間通訊機制,包括同乙個主機下的不同程序和網路主機間的程序通訊,如下圖所示:
無名管道是一類特殊的檔案,在核心中對應著一段特殊的記憶體空間,核心在這段記憶體空間中以迴圈佇列的方式儲存資料;無名管道的核心資源在通訊雙方退出後自動消失,無需人為**;
無名管道主要用於連通親緣程序(父子程序),用於雙方的快捷通訊,通訊為單向通訊
1. 建立:
pipe()pipedes[2]:儲存檔案描述符2. 讀寫:
讀程序寫程序
管道無資料
管道有資料
阻塞√立刻返回0
返回資料
阻塞√√
讀阻塞讀資料並返回
阻塞√收到sigpipe
訊號,write
返回-1
√阻塞√
寫入若滿,阻塞等待
3. 重定向:
所謂重定向,即關閉某個標準i/o裝置(stdin(0), stdout(1), stderr(2)), 而將某乙個普通的檔案描述符設定為0/1/2.
重定向,主要是採用dup
函式來實現的:
oldfd:原始檔的描述符(要求該檔案描述符必須有效,檔案必須處於開啟狀態)又稱fifo(fisrt in first out), 是磁碟上的乙個特殊檔案,沒有在磁碟儲存真正的資訊,其所儲存的資訊在記憶體中newfd
通訊雙方程序結束後,自動丟棄fifo中的資訊,但其在磁碟的檔案路徑本身依然存在
1. 建立 - mkfifo()
pathname: fifo檔案2. 讀寫:mode: 建立檔案的屬性(許可權)
讀程序寫程序
fifo無資料
fifo有資料√阻塞
阻塞√阻塞阻塞√√
寫入讀出(未滿,讀寫同時)√√x
即寫中途退出,讀直接返回0
same√x√
讀中途退出,寫返回sigpipe
same
access函式
pathname: 即檔名mode:測試的屬性
mode
description
f_ok
該檔案是否存在
r_ok
可讀w_ok
可寫x_ok
可執行bitwise
屬性(讀/寫/執行等)
/*
* filename: pipe.c
*/ #include #include //for pipe()
#include //for memset()
#include //for exit()
int main()
write(fd[1], "hello,world", 12);
memset(buf, '\0', sizeof(buf));
read(fd[0], buf, 12);
printf("the message is: %s\n", buf);
return 0;
}
程式的步驟:
建立乙個新的fifo檔案1. fifo_snd.c:fifo_snd.c檔案負責向fifo中寫入資料
fifo_rcv.c負責從fifo中讀取資料並列印
/*
*file: fifo_send.c
*/ #include #include #include #include #include #include #define fifo "/tmp/my_fifo"
int main()
//2. creat a fifo file
if(-1 == mkfifo(fifo, 0766))
the fifo file
int fifo_fd;
fifo_fd = open(fifo, o_wronly);
if(-1 == fifo_fd)
//4. write the fifo file
int num = 0;
num = write(fifo_fd, buf, sizeof(buf));
if(num < sizeof(buf))
printf("write the message ok!\n");
close(fifo_fd);
return 0;
}
2. fifo_rcv.c:
/*
*file: fifo_rcv.c
*/ #include #include #include #include #include #include #include #define fifo "/tmp/my_fifo"
int main()
the fifo file
int fifo_fd;
fifo_fd = open(fifo, o_rdonly);
if(-1 == fifo_fd)
//4. read the fifo file
int num = 0;
num = read(fifo_fd, buf, sizeof(buf));
printf("read %d words: %s\n", num, buf);
close(fifo_fd);
return 0;
}
Linux程序間通訊 管道
linux程序間通訊機制 1.同一主機程序間通訊機制 unix方式 有名管道fifo 無名管道pipe 訊號signal systemv方式 訊號量 訊息佇列 共享記憶體 2.網路通訊 rpc remote procedure call socket 管道管道是程序間通訊中最古老的方式,它包括無名管...
Linux程序間通訊 管道
管道 管道是一種最基本的程序間通訊機制,由pipe函式建立 include intpipe int filedes 2 呼叫pipe函式時在核心中開闢一塊緩衝區 稱為管道 用於通訊,它有乙個讀端乙個寫端,然後通過filedes引數傳出給使用者程式兩個檔案描述符,filedes 0 指向管道的讀端,f...
Linux 程序間通訊 管道
程序間通訊 a程序怎樣將 hello world 傳遞給b程序 i 利用檔案實現 需要乙個 中間人 進行傳遞 檔案 在磁碟中儲存 a先呼叫open函式開啟檔案,再用write函式寫檔案,b用read函式讀取檔案,但問題如下 1.如果a傳送了資料b進行了接收,但a的資料沒有被清空 2.如果a傳送了資料...