- 论坛徽章:
- 0
|
回复 9# folklore
管道应该不限制在父子进程间通信使用吧,在同一父进程创建的两个子进程之间也能互相通信吧,
int main()
{
int x1 = 0, x2 = 0, fd[2] = {0}, ret = 0;
char buf[50] = {0}, s[50] = {0};
pipe(fd);
while (-1 == (x1 = fork()));
if (0 == x1) {
printf("This is child 1\r\n");
sleep(5);
lockf(fd[1], 1, 0);
sprintf(buf, "This is message from child 1 \r\n");
write(fd[1], buf, 50);
lockf(fd[1], 0, 0);
exit(0);
} else {
while (-1 == (x2 = fork()));
if (0 == x2) {
printf("This is child 2\r\n");
sleep(5);
lockf(fd[1], 1, 0);
if (-1 == (ret = read(fd[0], s, 50))) {
printf("can't read pipe 2\r\n");
} else {
printf("childPID is %d, message%s", x2, s);
}
lockf(fd[1], 0, 0);
exit(0);
}
}
wait(0);
wait(0);
return 0;
//exit(0);
}
执行结果:
[root@localhost c_testy]# ./tst
This is child 1
This is child 2
childPID is 0, messageThis is message from child 1 |
|