Как я уже говорил, используйте сигнал SIGCHLD , например:
#include <stdio.h>
#include <signal.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
void handler(int sig)
{
pid_t chpid = wait(NULL);
/* WARNING : to show the call of the handler, do not do that
in a 'real' code, we are in a handler of a signal */
printf("Child pid %d ended (signal %s)\n", chpid, sig);
/* does 'something' to allow the parent to know chpid
terminated in a way compatible with parent requirement */
}
int main(void)
{
signal(SIGCHLD, handler);
if (!fork())
{
printf("Child pid is %d\n", getpid());
sleep(1);
return 0;
}
printf("Parent pid is %d\n", getpid());
getchar();
return 0;
}
Обратите внимание, что при поступлении сигнала необходимо позвонить wait (NULL) но поскольку по определению дочерний элемент завершается, функция немедленно возвращает
Компиляция и выполнение:
pi@raspberrypi:/tmp $ gcc -pedantic -Wall -Wextra s.c
pi@raspberrypi:/tmp $ ./a.out
Parent pid is 21743
Child pid is 21744
Child pid 21744 ended (signal 17)
<enter>
pi@raspberrypi:/tmp $
Конечно, сигнал 17 равен SIGCHLD , поскольку он является единственнымпрограмма ловит