虽然 " man waitpid" 里写明作用的对象是子进程, 我还是测试下是否可以 waitpid 子进程的子进程.
以下为测试代码, 其中用一块 sizeof(int) 大小的共享内存传递子进程的子进程 pid.
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <sys/ipc.h>
#include <sys/shm.h>
int main(int argc, char *argv[])
{
pid_t s_pid, ss_pid;
int shmid;
void *shm_ptr;
int *p_pid;
int ret;
shmid = shmget((key_t)getpid(), sizeof(int), 0660|IPC_CREAT);
if(shmid == -1)
{
printf("shmget failed\n");
return -1;
}
shm_ptr = shmat(shmid, NULL, 0);
if(shm_ptr == (void *)-1)
{
printf("shmat failed\n");
return -1;
}
p_pid = (pid_t *)shm_ptr;
*p_pid = 0;
s_pid = fork();
if(s_pid == 0)
{
ss_pid = fork();
//p_pid = (pid_t *)shm_ptr;
if(ss_pid == 0)
{
printf("ss process is pause ... \n");
pause();
}
else if(ss_pid > 0)
{
*p_pid = ss_pid;
printf("s process is pause ... \n");
pause();
}
else
{
printf("ss process fork failed\n");
exit(-1);
}
}
else if(s_pid < 0)
{
printf("s process fork failed\n");
exit(-1);
}
else
{
sleep(3);
while(1)
{
if((ret = waitpid(*p_pid, NULL, WNOHANG)) > 0)
{
printf("wait succeed, ss process %d exit\n", *p_pid);
exit(0);
}
else if(ret < 0)
{
perror("wait failed\n");
exit(-1);
}
else
{
printf("wait succeed, waiting %d\n", *p_pid);
sleep(5);
}
}
}
return 0;
}
结果输出: "No child process".
结论: 不可以waitpid 子进程的子进程.