国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > C > 正文

linux 匿名管道實例詳解

2020-01-26 14:04:00
字體:
供稿:網(wǎng)友

linux中進程的一種通信方式――匿名管道

pipe函數(shù)建立管道

調(diào)用pipe函數(shù)時在內(nèi)核中開辟一塊緩沖區(qū)(稱為管道)用于通信,它有一個讀端一個寫端,然后通過_pipe參數(shù)傳出給用戶程序兩個文件描述符,_pipe[0]指向管道的讀端,_pipe[1]指向管道的寫端。所以管道在用戶程序看起來就像一個打開的文件,通過read(_pipe[0]);或者write(_pipe[1]);向這個文件讀寫數(shù)據(jù)其實是在讀寫內(nèi)核緩沖區(qū)。pipe函數(shù)調(diào)用成功返回0,調(diào)用失敗返回-1。

1父進程調(diào)用pipe開辟管道,得到兩個文件描述符指向管道的兩端。

2. 父進程調(diào)用fork創(chuàng)建⼦進程,那么子進程也有兩個文件描述符指向同一管道。

3. 父進程關(guān)閉管道讀端,子進程關(guān)閉管道寫端。父進程可以往管道里寫,子進程可以從管道⾥讀,管道是用環(huán)形隊列實現(xiàn)的,數(shù)據(jù)從寫端流入從讀端流出,這樣就實現(xiàn)了進程間通信

匿名管道間的通信是單向的,并且是、只能是具有血緣關(guān)系的進程間通信

#include<stdio.h> #include<unistd.h> #include<string.h> #include<stdlib.h>  int main() {   int _pipe[2];   int ret = pipe(_pipe);   if (ret < 0)   {     perror("pipe");     return 1;   }   pid_t id = fork ();   if (id<0)   {     perror("fork");     return 2;   }   else if (id == 0)   {     // child     int count =5;     close (_pipe[0]);     char* msg = "hello bit";     while (count --)     {       write(_pipe[1],msg,strlen(msg));       sleep(1);     }     close (_pipe[1]);     exit(123);   }   else    {     // Father     close(_pipe[1]);     char buf[128];     while(1)     {       int count =5;       ssize_t s = read ( _pipe[0],buf,sizeof(buf)-1);       if (s<0)       {         perror("read");       }       else if(s==0)       {         printf("write is close/n");         return 2;       }       else       {         buf[s] ='/0';         printf ("child >> father: %s/n",buf);       }       count --;       if (count == 0)       {         close (_pipe[0]);         break;       }     }          int status = 0;     pid_t _wait = waitpid (id, &status,0);     if (_wait > 0)     {       printf("exit code is %d, signal is %d/n",           WIFEXITED(status), status & 0xff);     }      }        return 0; } 

感謝閱讀,希望能幫助到大家,謝謝大家對本站的支持!

發(fā)表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發(fā)表

圖片精選

主站蜘蛛池模板: 蓬溪县| 瑞安市| 凯里市| 富阳市| 芷江| 灵武市| 军事| 绥阳县| 青河县| 金沙县| 雷山县| 灵丘县| 屯留县| 大同市| 酉阳| 连山| 井陉县| 三都| 伽师县| 个旧市| 类乌齐县| 云南省| 扬州市| 屏南县| 紫金县| 搜索| 池州市| 宾川县| 四子王旗| 开鲁县| 连城县| 沛县| 谷城县| 广水市| 荆州市| 库尔勒市| 洞口县| 通渭县| 友谊县| 丰城市| 青岛市|