Question

int main() {
    int pid = fork();
    if(pid > 0){
        kill(pid, SIGKILL);
        printf("a");
    }else{
        /* getppid() returns the pid
        of the parent process */
        kill(getppid(), SIGKILL);
        printf("b");
    }
}

The Code Snippet could have a outcome of: nothing, a, b, ab, ba

I don't understand why nothing, ab and ba are possible.

int a = 1;
void handler(int sig){
    a = 0;
}
void emptyhandler(int sig){
}
int main() {
    signal(SIGINT, handler);
    signal(SIGCONT, emptyhandler);

    int pid = fork();
    if(pid == 0){
        while(a == 1)
            pause();
        printf("a");
    }else{
        kill(pid, SIGCONT);
        printf("b");
        kill(pid, SIGINT);
        printf("c");
    }
}

This one results in bac, bca.

Im not sure why "a process does not terminate" also valid? why would SIGINT kill it?

Was it helpful?

Solution

There's no telling which of the child/parent that gets run first. Or they may run in parallel if you have multiple cores , or the OS might interrupt them at any point of execution and run the other child or parent process (or some entierly other process). kill() is also asynchronous, it sends the signal, and it might be handled by the receiver later, after kill() returns.

Nothing: Parent gets killed right after it does kill(pid, SIGKILL);. Child gets killed right after it does kill(getppid(), SIGKILL);

"a": Child gets killed before or after it does kill(getppid(), SIGKILL);. Parent gets to run to completion.

"b": Parent gets killed before or after it does kill(pid, SIGKILL);. Child gets to run to completion.

"ab" Parent gets killed right after it prints "a" (or perhaps it manages to run to completion before the child signal arrives), child gets killed after it prints "b" (or perhaps it manages to run to completion before the parent signal arrives)

"ba" Same case as "ab", just that the child got scheduled to print "b" first.

OTHER TIPS

Sending signals does not constitute any kind of synchronisation between two processes. Only sending and receiving a signal lets you conclude that something (e.g. printing a) happens after something else (e.g. printing b). Both signals can be "in flight" and not received by anyone.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top