
正文
linux管道学习(一)
提示:扫一扫查出行【扫一扫了解最新限行尾号】
复制提示
最近学习了管道 pipe,在这里进行一下总结。
这里贴一段自己的实做代码
struct node{
int a;
long b;
};
int main()
{
int field[];
pid_t pid;
char buf[];
int returned_count;
pipe(field);
//fcntl(field[0], F_SETFL, O_NONBLOCK);
int status;
pid = fork();
if(pid < )
{
printf("Error In Fork\n");
exit();
}
if(pid == )
{
printf("In Child Process\n");
close(field[]);
node testnode;
testnode.a = ;
testnode.b = ;
//sleep(10);
//write(field[1],"This is a pipe test\n",strlen("This is a pipe test"));
//write(field[1],"This is another pipe test\n",strlen("This is another pipe test"));
write(field[],&testnode,sizeof(testnode));
testnode.a = ;
testnode.b = ;
write(field[],&testnode,sizeof(testnode));
exit();
}
else
{
printf("In Parent Process\n");
close(field[]);
//read(field[0],buf,sizeof(buf));
node ptestnode;
read(field[],&ptestnode,sizeof(node));
//printf("Msg %s from Child\n",buf);
printf("Msg From Child node a= %d, b= %ld\n",ptestnode.a,ptestnode.b);
read(field[],&ptestnode,sizeof(node));
printf("Msg From Child node a= %d, b= %ld\n",ptestnode.a,ptestnode.b);
//waitpid(pid,&status,0);
}
close(field[]);
}
pipe作为linux进程通讯中的一种常用手段被广泛使用,函数原型为int pipe(int filedes[2]); 其中filedes中的filedes[0]代表读 filedes[1]代表写。
再不使用fcntl函数限定的情况下,管道默认是以阻塞方式进行的。
比如父进程再使用read函数读取管道内容时,如果管道为空,则read函数会阻塞等待。如果将管道设置为读非阻塞,则父进程读取不到管道内容会直接进行下一步,不再等待。
但是父进程中如果使用了wait或waitpid函数,我发现实现效果依然和管道阻塞的情况一样,等待子进程写入,读取内容后才会进行下一步,这点有待研究。
通过read的返回值来进行判断管道中的内容是否读取完毕。
例如
node ptestnode;
int bufcount = ;
bufcount = read(field[],&ptestnode,sizeof(node));
//printf("Msg %s from Child\n",buf);
printf("Msg From Child node a= %d, b= %ld\n",ptestnode.a,ptestnode.b); while(bufcount)
{
bufcount = read(field[],&ptestnode,sizeof(node));
if(!bufcount)
{
break;
}
printf("Msg From Child node a= %d, b= %ld\n",ptestnode.a,ptestnode.b);
} printf("Pipe Read Over\n");






