匿名管道:
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46/* #include <unistd.h> int pipe(int pipefd[2]); 参数:int pipefd[2],传出参数 pipefd[0] 读端 pipefd[1] 写端 返回值: 成功返回0, 失败返回-1 注意匿名管道只能用于具有亲缘关系之间的通信(父子进程,兄弟进程) 管道默认是阻塞的,没有数据读阻塞,数据满了的话,写阻塞 */ //子进程发送数据给父进程,父进程读取之后输出 #include <unistd.h> #include <sys/types.h> #include <stdio.h> #include <stdlib.h> #include <string.h> int main(){ //fork之前创建pipe int pipefd[2]; int ret = pipe(pipefd); if(ret == -1){ perror("pipe"); exit(0); } //创建子进程 pid_t pid = fork(); if(pid > 0){ //父进程 char buf[1024] = {0}; int len = read(pipefd[0],buf,sizeof(buf)); printf("parent recv : %s, pid : %dn",buf,getpid()); } else if(pid == 0){ //子进程 sleep(10); char* str = "hello,i am a child"; write(pipefd[1],str,strlen(str)); } return 0; }
最后
以上就是清爽金毛最近收集整理的关于Linux编程之管道的全部内容,更多相关Linux编程之管道内容请搜索靠谱客的其他文章。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复