作爲一個簡單的例子,這應該給你一個關於這些系統調用如何協同工作的簡要概念。
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