|
5#

楼主 |
发表于 2009-7-23 17:44:24
|
只看该作者
通过管道的全双工通信
对一个管道来说,通信是半双工的( 一端只写不读,另一端只读不写 ),但是可以通过创建两个管道来实现全双工通信( 两端都可以读写 )。
测试代码:
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <unistd.h>
#include <string.h>
/*子进程读写管道函数*/
void child_rw_pipe(int writefd, int readfd)
{
char *message1 = "这是一条来自子进程的消息!\\n";
write(writefd, message1, strlen(message1)+1);
char message2[100];
read(readfd, message2, 100);
printf("子进程从管道中读取到的消息: %s", message2);
}
/*父进程读写管道函数*/
void parent_rw_pipe(int readfd, int writefd)
{
char *message1 = "这是一条来自父进程的消息!\\n";
write(writefd, message1, strlen(message1)+1);
char message2[100];
read(readfd, message2, 100);
printf("父进程从管道中读取到的消息: %s", message2);
}
int main(void)
{
int pipefd1[2], pipefd2[2];
pid_t pid;
int stat_val;
printf("全双工通信:\\n\\n");
if (pipe(pipefd1)) {
printf("管道-1创建失败\\n");
exit(1);
}
if (pipe(pipefd2)) {
printf("管道-2创建失败\\n");
exit(1);
}
pid = fork();
switch(pid) {
case -1:
printf("创建进程失败\\n");
exit(1);
case 0:
/*子进程关闭 pipefd1 读端,关闭 pipefd2 的写端*/
close(pipefd1[0]);
close(pipefd2[1]);
child_rw_pipe(pipefd1[1],pipefd2[0]);
exit(0);
default:
/*父进程关闭 pipefd1 写端,关闭 pipefd2 的读端*/
close(pipefd1[1]);
close(pipefd2[0]);
parent_rw_pipe(pipefd1[0], pipefd2[1]);
wait(&stat_val);
exit(0);
}
} |
|
|