码迷,mamicode.com
首页 > 系统相关 > 详细

linux管道学习(二)

时间:2016-07-01 11:40:50      阅读:197      评论:0      收藏:0      [点我收藏+]

标签:

 1 int main()
 2 {
 3     char* pipename = "pipe";
 4     mkfifo(pipename,0777);
 5     int pid = fork();
 6     if(pid < 0)    
 7     {
 8         printf("Error In Fork\n");
 9         exit(-1);
10     }
11 
12     if(pid == 0)
13     {
14         printf("In Child Process\n");
15         int fd = open(pipename,O_WRONLY|O_NONBLOCK);
16         node testnode;
17         testnode.a = 10;
18         testnode.b = 20;
19         
20         write(fd,&testnode,sizeof(testnode));
21 
22         testnode.a = 11;
23         testnode.b = 22;
24 
25         write(fd,&testnode,sizeof(testnode));
26 
27         close(fd);
28         printf("Child Process Is Over \n");
29     }
30     if(pid > 0)
31     {
32         
33         printf("In Parent Process\n");
34         
35         int fd = open(pipename,O_RDONLY);
36 
37         node testnode;
38         read(fd,&testnode,sizeof(node));
39         printf("Msg From Child node a = %d,b = %ld \n",testnode.a,testnode.b);
40 
41         read(fd,&testnode,sizeof(node));
42         printf("Msg From Child node a = %d,b = %ld \n",testnode.a,testnode.b);
43 
44         close(fd);
45         
46         waitpid(pid,NULL,0);
47         printf("Praent Process Is Over \n");
48     }
49 
50     
51 }


在阻塞情况下,管道会阻塞直到有内容写入

读取时如果管道为空会等待有内容可以读取

在打开管道的时候可以选择非阻塞方式O_NONBLOCK

如果是非阻塞方式则忽略当前管道状态

命名管道不仅可以在有亲缘关系的进程中进行通信,也可以在无亲缘关系的进程中通信。

linux管道学习(二)

标签:

原文地址:http://www.cnblogs.com/boyunzheyue2/p/5632349.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!