直接看代码, 里面已经有注释了。
主程序:
int main()
{
char buf[256];
int fdin[2];
int fdout[2];
int pid;
int size;
// 创建全双工管道
pipe(fdin);
pipe(fdout);
pid = fork();
if (pid == 0){
// 子进程...
close(fdin[1]); // 子进程用不了fdin的输出
close(fdout[0]);
// 重定向标准输入和标准输出到管道
// 子进程从标准输入(fdin[0])读取,主进程往fdin[1]写入
// 子进程向标准输出(fdout[1]写入),主进程从fdout[0]读取
if (dup2(fdin[0], STDIN_FILENO) != STDIN_FILENO
|| dup2(fdout[1], STDOUT_FILENO) != STDOUT_FILENO) {
fprintf(stderr, "dup2() failed!\n");
}
close(fdin[0]);
close(fdout[1]);
// 执行外部程序 test2
execlp("./test2", "test", NULL);
fprintf(stderr, "Failed to execlp(): %s\n", errno);
exit(0);
}
// 发送 "Hello world" 给子进程,
// 子进程可以从fdin[0]读取
write(fdin[1], "Hello world", strlen("Hello world"));
// 读取从子进程写入fdout[1]的消息
size = read(fdout[0], buf, sizeof(buf)-1);
buf[size] = '\0';
fprintf(stderr, "buf = %s\n", buf);
sleep(1);
if (kill(pid, SIGQUIT) != 0)
fprintf(stderr, "Failed to kill pid %d: %s\n", pid, strerror(errno));
// 等待子进程退出
fprintf(stderr, "Waiting for exiting....\n");
waitpid(pid, NULL, 0);
fprintf(stderr, "Exiting....\n");
// 关闭文件句柄
close(fdout[0]);
close(fdin[1]);
return 0;
}
外部程序
int main()
{
fd_set rfds;
int fd = fileno(stdin);
int ret;
char buf[256];
FD_ZERO(&rfds);
FD_SET(fd, &rfds);
// 从主进程读取消息(已经重定向到标准输入)
ret = select(fd+1, &rfds, NULL, NULL, NULL);
if (ret > 0) {
int len = read(fd, buf, 255);
buf[len] = '\0';
}
fprintf(stderr, "%s: %d\n", __FILE__, __LINE__);
// 发送消息给主进程(重定向到标准输出)
fprintf(stdout, "--->Message: %s!\n", buf);
fflush(stdout);
// while (1) sleep(1);
return 0;
}