linux 匿名管道实例详解
发布时间:2021-01-10 11:25:02 所属栏目:创业 来源:网络整理
导读:linux中历程的一种通讯方法――匿名管道 pipe函数成立管道 挪用pipe函数时在内核中开发一块缓冲区(称为管道)用于通讯,它有一个读端一个写端,然后通过_pipe参数传出给用户措施两个文件描写符,_pipe[0]指向管道的读端,_pipe[1]指向管道的写端。以是管道在用户
|
linux中历程的一种通讯方法――匿名管道 pipe函数成立管道 挪用pipe函数时在内核中开发一块缓冲区(称为管道)用于通讯,它有一个读端一个写端,然后通过_pipe参数传出给用户措施两个文件描写符,_pipe[0]指向管道的读端,_pipe[1]指向管道的写端。以是管道在用户措施看起来就像一个打开的文件,通过read(_pipe[0]);可能write(_pipe[1]);向这个文件读写数据着实是在读写内核缓冲区。pipe函数挪用乐成返回0,挪用失败返回-1。 1父历程挪用pipe开发管道,获得两个文件描写符指向管道的两头。 2. 父历程挪用fork建设⼦历程,那么子历程也有两个文件描写符指向统一管道。 3. 父历程封锁管道读端,子历程封锁管道写端。父历程可以往管道里写,子历程可以从管道⾥读,管道是用环形行列实现的,数据从写端流入从读端流出,这样就实现了历程间通讯 匿名管道间的通讯是单向的,而且是、只能是具有血缘相关的历程间通讯
#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 closen");
return 2;
}
else
{
buf[s] =' ';
printf ("child >> father: %sn",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 %dn",WIFEXITED(status),status & 0xff);
}
}
return 0;
}
感激阅读,但愿能辅佐到各人,感谢各人对本站的支持! (编辑:湖南网) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |


