作为一个简单的例子,这应该给你一个关于这些系统调用如何协同工作的简要概念。
void spawn(char *program,char *argv[]){
if(pipe(pipe_fd)==0){
char message[]="test";
int write_count=0;
pid_t child_pid=vfork();
if(child_pid>0){
close(pipe_fd[0]); //first close the idle end
write_count=write(pipe_fd[1],message,strlen(message));
printf("The parent process (%d) wrote %d chars to the pipe \n",(int)getpid(),write_count);
close(pipe_fd[1]);
}else{
close(pipe_fd[1]);
dup2(pipe_fd[0],0);
printf("The new process (%d) will execute the program %s with %s as input\n",(int)getpid(),program,message);
execvp(program,argv);
exit(EXIT_FAILURE);
}
}
}
你走多远了?你能告诉我们一些你写的代码吗? – 2011-06-15 22:46:54
你只想让你的程序能够在管道中工作吗?然后,只需从'stdin'中读取并写入'stdout',就可以自动获得该行为。 – 2011-06-15 23:14:03