Linux 匿名管道通信概述
在 Linux 操作系统中,匿名管道是进程间进行数据交换的一种重要通信手段。
要实现管道的建立,需调用 pipe 系统调用函数。
当程序执行 pipe 函数时,内核会在内存中分配一块特定的缓冲区,这块区域即被称为管道。该缓冲区具备两个操作端口:一个用于读取,另一个用于写入。函数通过 _pipe 参数向用户空间返回两个文件描述符:_pipe[0] 关联至管道的读取端,而 _pipe[1] 则关联至写入端。因此,在应用程序的视角中,管道表现为一个已打开的文件实体。对 _pipe[0] 执行 read 操作或对 _pipe[1] 执行 write 操作,实质上是在对内核中的缓冲区进行数据的读写交互。若 pipe 函数执行成功,将返回数值 0;若遭遇失败,则返回 -1。
第一步,父进程首先调用 pipe 函数以开辟管道资源,此时获取指向管道两端的两个文件描述符。
第二步,父进程接着调用 fork 函数来生成子进程。由于继承特性,新创建的子进程也拥有指向同一管道资源的两个文件描述符。
第三步,为了确立通信方向,父进程应当关闭管道的读端,而子进程则需关闭管道的写端。经过此配置,父进程获得写入权限,子进程获得读取权限。鉴于管道内部采用环形队列结构进行数据存储,数据从写入端进入并从读取端流出,从而完成进程间的数据传输。
匿名管道所支持的通信模式为单向传输,且严格限制于存在血缘关系(如父子或兄弟进程)的进程之间。
#include
#include
#include
#include
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;
}

感谢您的阅读,希望上述内容能为您提供帮助,同时也感谢大家对本站的支持!