If you send SIGTERM from the parent, the final result depends on the order in which the processes are planned.
If the child is first scheduled, everything works:
+---------------+ | pid = fork(); | +-------+-------+ parent | child +-----------------------------+-----------------------------+ | | | +-------------------------+--------------------------+ | | if (signal(SIGTERM, stopChild) == SIG_ERR) { | | | printf("Could not attach signal handler\n"); | | | return EXIT_FAILURE; | | | } | | +-------------------------+--------------------------+ | | . . . . . . | | +-------------------------+--------------------------+ | | if (signal(SIGTERM, stopChild) == SIG_ERR) { | | | printf("Could not attach signal handler\n"); | | | return EXIT_FAILURE; | | | } | | +-------------------------+--------------------------+ | | | | | | | +-------------+-------------+ | | if (pid > 0) { | | | kill(pid, SIGTERM); | | | } | | +-------------+-------------+ | | | | | | |
But if you assign a guy first, the child may not have time to configure the signal handler:
+---------------+ | pid = fork(); | +-------+-------+ parent | child +-----------------------------+-----------------------------+ | | +-------------------------+--------------------------+ | | if (signal(SIGTERM, stopChild) == SIG_ERR) { | | | printf("Could not attach signal handler\n"); | | | return EXIT_FAILURE; | | | } | | +-------------------------+--------------------------+ | | | | | | | +-------------+-------------+ | | if (pid > 0) { | | | kill(pid, SIGTERM); | | | } | | +-------------+-------------+ | | | . . . . . . | | | +-------------------------+--------------------------+ | | if (signal(SIGTERM, stopChild) == SIG_ERR) { | | | printf("Could not attach signal handler\n"); | | | return EXIT_FAILURE; | | | } | | +-------------------------+--------------------------+ | | | | | |
This is called a race condition because the end result depends on who starts first.
ninjalj
source share