why the child process doesn't resume after I send SIGCONT to it?

Viewed 389

I'm new to C and processes, sorry if my question sounds dumb. below is my code:

int main()
{   
    pid_t pid; 
    
    if ((pid = fork()) == 0){
        pause();
        printf("child process restarts!\n");
        exit(0);
    }

    kill(pid, SIGCONT);
    exit(0);
}

so in the parent process, I did send SIGCONT to the child process, so the child process suspended by pause shoud resume, but I didn't see any output printed, which means the child process hasn't restarted? so how can I resume the child process?

1 Answers

Like said in man pause, you need to catch SIGCONT:

   pause() causes the calling process (or thread) to sleep until a
   signal is delivered that either terminates the process or causes the
   invocation of a signal-catching function.

Adding that and sleep(1) in the parent to make sure the child process has completely initialized when kill() is called, you will get the desired output:

#include <stdio.h>
#include <stdlib.h>
#include <signal.h>
#include <unistd.h>

static void catch( int sig ) { }

int main()
{
    pid_t pid;

    if ((pid = fork()) == 0){
        signal( SIGCONT, catch );
        pause();
        printf("child process restarts!\n");
        exit(0);
    }

    sleep( 1 );
    kill(pid, SIGCONT);
    exit(0);
}

Because of the special meaning of SIGCONT together with SIGSTOP or SIGTSTP you might want to use another signal together with pause(), like SIGUSR1

Related