想实现 ./pipe args[1] args[2],使其实现管道的功能
if ( pid == 0 ){ /* parent will exec av[2] */
close(pipe_in[1]); /* parent doesn't write to pipe */
close(pipe_out[0]);
dup2(pipe_out[1],1);
dup2(pipe_in[0], 0) ;
close(pipe_out[1]);
close(pipe_in[0]); /* stdin is duped, close pipe */
execl("/home/heey/webserver/web5/www/hello", "hello", NULL);
}
close(pipe_out[1]);
close(pipe_in[0]);/* child doesn't read from pipe */
write(pipe_in[1],av[1],strlen(av[1]));
char c;
while(read(pipe_out[0],&c,1)>0)
printf("%c",c);
close(pipe_out[0]);
close(pipe_in[1]); /* stdout is duped, close pipe */
waitpid(pid,&status,0);
父进程从管道pipe_in[1]写端写入数据,而进程中pipe_in[0]重定向到标准输入,即在执行execl时,管道pipe_in里面的内容可以作为hello的标准输入,而不是作为hello的参数,在hello的原代码中加入标准输入就可以读取管道pipe_in的内容,这个当时弄了很久才发现,hello是可以执行的文件,而execl后,即可执行文件hello的输出,输入到管道pipe_out[1]中,因为子进程的标准输出重定向到管道pipe_out的标准输入,再在子进程中读取管道pipe_out[0]的内容即可