日期:2014-05-16  浏览次数:20772 次

关于子进程返回PID的问题
相关文件在附件里面
程序需在Linux或Unix下运行
问题是这样的,我想通过调用loonybin3.cpp建立5个子进程来执行loony,然后通过loony返回的status来确定loony是正常退出,异常推出,还是被信号kill了。然后显示每个子进程结束时的情况,包括process id以及退出时的情况是怎么样的。
但是有个问题在这里就是:我一共建了5个子进程,但是显示结果上每个子进程的process id都是相同的,照例说子进程process id应该不一样啊,请高手帮我解答下好么。

------解决方案--------------------
for ( int i = 0; i < 5; i++)
{
if( (pid = fork()) == 0 ) { //child process
execl(buff, buff, parm[i], 0);
printf("Sorry, the execl failed.\n");
exit(1);
}

/* parent process */
wait(&status);

// if child process exits normally, and if the status value of exit(status) in child process is 0, 
// print message of case 1; if child process exit abnormally, then exit status is > 0, print message of case 2
if(WIFEXITED (status))
if (WEXITSTATUS(status) == 0 ) //case 1
printf("=== %s (pid %ld): Normal exit ===\n", parm[i], getpid() );
else //case 2
printf ("=== %s (pid %ld): Exit code %i ===\n", parm[i], getpid(), WEXITSTATUS(status) );

//if child process is killed by signal and print what type of signal kill the child process
if (WIFSIGNALED(status))
printf ("=== %s (pid %ld): Signalled: %s ===\n", parm[i], getpid(), strsignal( WTERMSIG(status) ) );
}//end of for loop
================================================
getpid()返回的是当前进程的PID, 在楼主的程序里,用pid变量就可以了(也就是fork()返回的那个值)。