標籤:pop 相關 目錄 影響 cal 注意 標頭檔 href set
一,定義:
管道又可以分為無名管道和具名管道,兩者的用途是不一樣的。
無名管道PIPE:主要用於具有親緣關係的進程之間的通訊,無名管道的通訊是單向的,只能由一段到另外一段;無名管道是臨時性的,完成通訊後將自動消失。一般採用先建立無名管道,再建立子進程,使子進程繼承父進程的管道檔案描述符,從而實現父子進程間的通訊;在非親緣關係管道之間,如果想利用無名管道進行通訊,則需要藉助另外的檔案描述符傳遞機制。
有名管道FIFO:有名管道是一個實際存在的特殊檔案,利用有名管道可以實現同主機任意進程之間的資料互動。
二,應用:
1,Shell中的無名管道
在Shell命令列中使用無名管道是到過管道符“ | ” 實現的。如ps -ax|grep mysql, 將ps -ax的內容通過管道傳給grep mysql
2.建立無名管道
(1.)函數:
pipe(建立管道):
1) 標頭檔
#include<unistd.h>
2) 原型:
int pipe(int filedes[2]);
3) 函數說明:
pipe()會建立管道,並將檔案描述詞由參數filedes數組返回。
filedes[0]為管道裡的讀取端
filedes[1]則為管道的寫入端。
4) 傳回值:
若成功則返回零,否則返回-1,錯誤原因存於errno中。
5)錯誤碼:
EMFILE 進程已用完檔案描述詞最大量
ENFILE 系統已無檔案描述詞可用。
EFAULT 參數 filedes 數組地址不合法。
(2)使用:
#include<stdio.h> #include<unistd.h> #include<string.h> int main() { int p[2]; int pid; char *str = "HelloWorld"; char buf[128]; memset(buf,‘\0‘,128); if(pipe(p) == -1) { printf("function pipe() calls failed."); return -1; } if((pid=fork()) == -1) //建立一個子進程 { printf("function fork() calls failed.\n"); return -1; } else if(pid == 0) //在子進程中 { printf("In sub : pid=%d\n",getpid()); write(p[1],str,strlen(str)); //向無名管道中寫入str }else { //在父進程中 printf("In father : pid=%d\n",getpid()); read(p[0],buf,strlen(str)); //讀取無名管道 printf("In father : buf=%s\n",buf); } }
結果:
注意:read和write為阻塞模式
3.建立有名管道
(1)函數:mkfifo(建立具名管道)
相關函數 pipe,popen,open,umask
1)表標頭檔
#include<sys/types.h>
#include<sys/stat.h>
2)函數原型
int mkfifo(const char * pathname,mode_t mode);
3)函數說明
mkfifo()會依參數pathname建立特殊的FIFO檔案,該檔案必須不存在,而參數mode為該檔案的許可權(mode%~umask),因此umask值也會影響到FIFO檔案的許可權。
4)傳回值 若成功則返回0,否則返回-1,錯誤原因存於errno中。
5)錯誤碼
EACCESS 參數pathname所指定的目錄路徑無可執行檔許可權
EEXIST 參數pathname所指定的檔案已存在。
ENAMETOOLONG 參數pathname的路徑名稱太長。
ENOENT 參數pathname包含的目錄不存在
ENOSPC 檔案系統的剩餘空間不足
ENOTDIR 參數pathname路徑中的目錄存在但卻非真正的目錄。
EROFS 參數pathname指定的檔案存在於唯讀檔案系統內。
(2)使用:
#include<sys/types.h>#include<sys/stat.h>#include<fcntl.h>main(){ char buffer[80]; int fd; unlink(FIFO); mkfifo(FIFO,0666); if(fork()>0) { char s[ ] = “hello!\n”; fd = open (FIFO,O_WRONLY); write(fd,s,sizeof(s)); close(fd); } else { fd= open(FIFO,O_RDONLY); read(fd,buffer,80); printf(“%s”,buffer); close(fd); }}
參考:linux c 中文函數手冊
linux 處理序間通訊機制(IPC機制)- 管道