c - How can child kill parent process while parent process waits until child process to terminate? -


i not understand following code:

pid_t pid; int counter = 0; void handler1(int sig) {   counter++;   printf("counter = %d\n", counter);   fflush(stdout);   kill(pid, sigusr1); } void handler2(int sig) {   counter += 3;   printf("counter = %d\n", counter);   exit(0); } int main() {   signal(sigusr1, handler1);   if ((pid = fork()) == 0) {     signal(sigusr1, handler2);     kill(getppid(), sigusr1);     while (1) {     };   } else {     pid_t p;     int status;     if ((p = wait(&status)) > 0) {       counter += 2;       printf("counter = %d\n", counter);     }   } } 

how can child process kill parent process while parent process waits until child process terminates?

note first kill() syscall misnamed, general-purpose function sending signal process. killing target process 1 of several possible results.

more generally, however, signal handling is interrupt mechanism. great many library functions, including wait() can interrupted receipt of signal. control passes registered handler signal, if any, or else default action performed. afterward, function interrupted returns, indicating error via return code , / or setting errno.

edited add: additionally, own code may interrupted receipt of signal. provided effect not terminate process, execution resume @ point left off if signal handler exits normally, or @ other point if handler exits calling longjmp().

also, signal delivery asynchronous mechanism handled kernel. process can blocked or otherwise occupied , still receive signals; indeed, that's big part of point of them. each process has queue of pending signals awaiting handling; processes, queue empty time, unless explicitly block signals, never safe process assume not receive (and signals cannot blocked anyway).

in particular code, main process starts setting function1() handler signal usr1. forks, , child process sets function function2() its handler signal usr1 (not thereby affecting parent), sends signal usr1 parent, , goes infinite loop.

meanwhile, parent initiates wait() child process. interrupted receipt of signal. wait end after signal received , registered handler runs, wait() returning -1 , setting errno eintr. 1 of actions handler performs send sigusr1 child.

upon receiving signal, child's normal flow of execution interrupted run handler, function2(). updates the child's copy of variable counter, prints value, , exit()s.

end result:

the main process prints

counter = 1

then exits. child process prints

counter = 3

then exits.


Comments

Popular posts from this blog

facebook - android ACTION_SEND to share with specific application only -

python - Creating a new virtualenv gives a permissions error -

javascript - cocos2d-js draw circle not instantly -