Search code examples
cprocesssignals

How to correctly send SIGTSTP signal to a child process?


I am writing a custom shell program for an assignment where I do fork() and exec(). What I want to do is handle the signal SIGTSPS so that it suspends the child process.

I am currently handling crtl z with

 void SIGTSTP_Handler(){

if (child != 0) {
    kill(child, SIGTSTP);
    }
}

and my parent process waitpid with

if (waitpid(child, &status, WUNTRACED |WCONTINUED ) == -1) {
        err(-1, "Failed to waitpid()");
    }
if(WIFSTOPPED(status))
{

    printf("child stop with code: %d\n", WIFSTOPPED(status));
}

when I press ctrl Z my process stop but it exit with code 1. which means error. I want to be able to suspend the child process and resume it if i pass it a CONT signal. How do i properly handthe ctrl Z so that it suspend the child process and if I input fg it will put the suspend process back into running?

sleep 10
PID 71740: I must be the parent!
^Z
71740child stop with code: 1

Solution

  • Your child process is stopped, not exited. If it had exited, WIFSTOPPED(status) would be 0 and WIFEXITED(status) would be nonzero.

    To continue the process, when your fg command is executed, send the SIGCONT signal to the child:

    kill(child, SIGCONT)