linux管道编程 100求解..

创建管道 派生一个子进程 执行cat程序 父进程接受用户从终端输入的任何内容 通过管道传递给子进程的cat程序
麻烦给详细点...我基本完全不懂啊 谢谢

//具体不懂得地方你晚上再问我吧
#include<unistd.h>
#include<stdio.h>
#include<sys/types.h>
#include<stdlib.h>
#include<fcntl.h>
#include<string.h>

int main(int argc, char *argv) {
int fd[2];
int len;
pid_t pid;
char filename[10];
char childbuf[10];
if (pipe(fd) < 0) {
perror("pipe error!");
exit(1);
}
if ((pid = fork()) < 0) {
perror("fork error!");
exit(1);
}
if (pid == 0) {

close(fd[1]);
len = read(fd[0], childbuf, 100);
childbuf[len] = '\0';
printf("%s\n", childbuf);
if (execlp("cat", "cat", childbuf, (char*) 0) < 0) {
perror("exec error!");
exit(1);
}
} else {
close(fd[0]);
printf("请输入文件名\n");
scanf("%s", filename);
write(fd[1], filename, strlen(filename));
waitpid(pid, NULL, 0);
return 0;
}
}
温馨提示:答案为网友推荐,仅供参考
第1个回答  2009-05-23
给你提供一下大概步骤:
int child_pid;
int fds[2];
pipe(fds);
if ( (child_pid = fork()) == 0) { //子进程
close(fds[1]);// 子进程关闭掉管道的写端
dup2(fds[0], 0); //用管道的读端代替原来的标准输入
调用exec函数族中的一个来执行cat;
exit(0);
} else if (child_pid > 0) { //父进程
close(fds[0]); //父进程关闭读段
从标准输入读入数据;
然后write(fds[1], ...);
} else { //error
...
}

参考资料:http://www.xueyusi.com

相似回答