我寫了一個程序,它模擬'$ ls -l | wc -c'就像使用管道的命令一樣。 現在我無法找到應該在這段代碼中使用waitpid或waitpid的位置。我應該在這段代碼中使用waitpid和waitpid?
另外我應該關閉管道? 請查看我的代碼並提出建議。
int main ( int argc , char *argv[])
{
char *cmd_one_tokens[MAX]; /* Array of pointer to hold tokens of first command */
char *cmd_two_tokens[MAX]; /* Array of pointer to hold tokens of second command */
pid_t pid_one = -1 , /* variable to hold process id of first sub process */
pid_two = -1 ; /* variable to hold process id of second sub process */
int status = -1 ; /* variable to read the status of the child process */
int pipe_fd[2] = {-1,-1}; /* Array to hold descriptors returned by pipe sys call */
int ret_val =-1 ; /* variable to hold return values by system calls */
/*Validate Number of command line arguments */
if(3 != argc)
{
printf("Provide Appropriate Arguments \n <lab3> < \"arg1\" > < \"arg2\" > \n");
_exit(FAILURE);
}
/*Parse first command and get the tokens */
parse_command(argv[1],cmd_one_tokens);
/*Parse second command and get the tokens */
parse_command(argv[2],cmd_two_tokens);
/* Create pipe */
ret_val=pipe(pipe_fd);
/*Error check */
if(ERROR==ret_val)
{
perror("Pipe creation error \n");
_exit(FAILURE);
}
/*Fork First Child */
pid_one = fork() ;
//Error check
if(0 == pid_one) /*child process block */
{
/* redirect stdout to pipe's write end for sub process one*/
dup2(pipe_fd[1],1);
/*close pipe read end */
close(pipe_fd[0]);
execvp(cmd_one_tokens[0],cmd_one_tokens);
/* if execvp returns then if must have failed */
//Error check
}
else /*main process block */
{
/*Wait for first sub process to finish */
waitpid (pid_two , &status ,0); // <-------changes
/*Fork second subprocess */
pid_two = fork();
//Error check
if(0 == pid_two) /*second child process block */
{
/* redirect stdin to pipe's read end for sub process two */
dup2(pipe_fd[0],0);
/*close pipe write end */
close(pipe_fd[1]);
execvp(cmd_two_tokens[0] , cmd_two_tokens);
/* if execvp returns then if must have failed */
//Error check
}
else /*main process block */
{
status=-1; /*reset status */
/*Waiting for the second sub process to finish in No hang fashion */
waitpid (pid_two , &status ,0); // <-------changes
}
}
return(SUCCESS);
}/*End of main */
我真的希望你採取了[我上次的建議](http://stackoverflow.com/questions/5610184/input-redirection-problem-while-using-execvp/5610320#5610320)並檢查返回值從'fork(2)'發佈錯誤再次發佈。 – sarnold 2011-04-10 10:07:26
是的,我已經做到了。我試圖正確地把等待,有時它的工作很好,有一段時間它給了pipe_w在ps .... – Muse 2011-04-10 10:17:36