linux 匿名管道實例詳解
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;
}

感謝閱讀,希望能幫助到大家,謝謝大家對本站的支持!
相關(guān)文章
基于C++的農(nóng)夫過河問題算法設(shè)計與實現(xiàn)方法
這篇文章主要介紹了基于C++的農(nóng)夫過河問題算法設(shè)計與實現(xiàn)方法,簡單描述了農(nóng)夫過河問題,并結(jié)合實例形式詳細分析了基于C++實現(xiàn)農(nóng)夫過河問題的相關(guān)算法實現(xiàn)步驟與操作技巧,需要的朋友可以參考下2017-09-09

