So I'm trying to implement a signal handler for the SIGTSTP signal in a child process.
Basically what I'm trying to achieve is this:
- Start child Process
- Make the parent wait on the child process
- call Sleep on the Child process for x seconds.
- Before the sleep finishes execution, I want to send a Ctrl+Z signal. This signal should stop the child process, but resume the parent process. The parent process should then know the process id of the stopped process.
I run it using the command: ./testsig sleep 10
This is my code so far:
#include<stdlib.h>
#include<stdio.h>
#include<signal.h>
#include<string.h>
volatile sig_atomic_t last_proc_stopped;
volatile sig_atomic_t parent_proc_id;
void handle_stp(int signum)
{
if(getpid()==parent_proc_id)
{
kill(parent_proc_id,SIGCONT);
signal(SIGTSTP,handle_stp);
}
else
{
last_proc_stopped=getpid();
kill(parent_proc_id,SIGCONT);
}
}
void main(int argc, char *argv[])
{
int childid=0,status;
signal(SIGTSTP,SIG_IGN);
parent_proc_id=getpid();
childid=fork();
if(childid>=0)
{
if(childid==0)//child
{
signal(SIGTSTP,handle_stp);
strcpy(argv[0],argv[1]);
strcpy(argv[1],argv[2]);
argv[2]=NULL;
printf("Passing %s %s %s\n",argv[0],argv[1],argv[2]);
execvp(argv[0],argv);
}
else
{
wait(&status);
printf("Last Proc Stopped:%d\n",last_proc_stopped);
}
}
else
{
printf("fork failed\n");
}
}
Currently, it seems like ctrl+Z has some kind of effect (but definitely not the one I want!)
When I hit ctrl+Z in the middle of the child executing sleep, the cursor continues to blink for the remainder of the (in my case 10) seconds, but control does not reach the parent process.
Without hitting ctrl+Z, control returns to the parent as expected.
What am I doing wrong?
I have seen this answer as well, but I'm not really able to understand it:
After suspending child process with SIGTSTP, shell not responding