跳到内容
首页
学编程
学软件
学电脑
服务器
搜索
进程间通信:管道 专职C++ C++博客
进程间通信:管道
翻开高级unix编程,仔细看了一下管道,并将书中的例子修改并实现。
虽然很简单,确揭示了多进程编程的基础。
用管道非常真是非常的简单。以前只是看了,没有实践!
#include
<
common.h
>
#define
MAXLINE256
int
main(
int
argc,
char
*
argv[])
{
int
fd[
2
];
//
管道fd
pid_tpid;
//
子进程的PID
char
line[MAXLINE];
if
((pipe(fd))
<
0
)
//
创建PID,其中fd[0]为读管道,fd[1]为写管道
{
cout
<<
"
pipeerror
"
<<
endl;
exit(
0
);
}
if
((pid
=
fork())
<
0
)
//
创建子进程
{
cout
<<
"
forkerror
"
<<
endl;
//
一般是进程过多的时候才会出错
exit(
0
);
}
//
执行fork后,当前进程会得到子进程的pid,而子进程得到的是0,可以通过getppid()取得父进程
if
(pid
>
0
)
{
//
父进程向管道写数据
char
buffer[MAXLINE];
close(fd[
0
]);
cout
<<
"
input:
"
;
cin.getline(buffer,MAXLINE);
write(fd[
1
],buffer,strlen(buffer));
}
else
{
//
子进程接收数据
close(fd[
1
]);
int
n
=
read(fd[
0
],line,MAXLINE);
line[n]
=
0
;
cout
<<
"
readmessage:
"
<<
line
<<
endl;
}
return
0
;
}
标签
define
,
return
,
修改
,
进程
发表回复
取消回复
要发表评论,您必须先
登录
。