Search code examples
clinuxsignalspause

Sending signal to child process on pause


My aim is to pause child process after its creation. Then I want to interrupt pause and I do it by a signal that I send from the parent process via kill(). The main question is where I should put pause() in this situation.

This is what I've got so far:

int main()
{
    int pid;

    if ((pid = fork()) < 0) //error occured
    {
        perror("fork");
        exit(1);
    }

    if (pid == 0) //___Child___
    {
        signal(SIGHUP, sighup);
        printf("Tryna work with pause():\n");
        printf("Before pause:\n");
        pause();
        printf("After pause.\n");

        for(;;) //infinite loop
            ;
    }

    else //___Parent___
    { /* pid hold id of child */
        printf("\nPID=%d\n\n",pid);
        printf("\nPARENT: sending SIGHUP\n\n");
        kill(pid, SIGHUP);

        sleep(3); //wait 3 secs
    }
}

void sighup()
{
    signal(SIGHUP, sighup) //reset signal;
    printf("In handler...");
}

Call it in Linux terminal like main 5053 and the output is:

PID=1939

PARENT: sending SIGHUP

Solution

  • The only thing to change is move kill after the sleep to give child process time to run.

    {
        ...
        printf("\nPARENT: sending SIGHUP\n\n");
        kill(pid, SIGHUP);
    
        sleep(3); //wait 3 secs
        ...
    }