My Goal: I have a simple c program that should overwrite the default SIGTSTP handler with my own, and send a SIGTSTP only to the child process.
My Issue: The kill call within the SIGTSTP handler stops the parent process, and exits my program (not just the child). What am I doing wrong?
Edit: This problem seems to only happen when I compile and run my code using the following make command: gcc -o program *.c -lreadline && ./program
. It seems (the make
process?) is terminated because my output contains the following line upon ctrl-z:
gcc -o sandbox *.c -lreadline && ./sandbox
Is there a way to both get my program to have the desired functionality and use make?
My Code:
#include <stdio.h>
#include <signal.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <string.h>
#include <stdlib.h>
#include <readline/readline.h>
int child;
void handler();
static void SIGTSTP_Handler()
{
if (child != 0) {
kill(child, SIGTSTP);
}
}
int main(void)
{
signal(SIGTSTP, SIGTSTP_Handler);
child = fork();
if (child == 0) {
setpgid(0, getpid());
printf("CHILD's PID ::: [ %d ]\n", getpid());
printf("CHILD's GROUP ::: %d\n", getpgrp());
execlp("sleep", "sleep", "30", NULL);
}
else {
setpgid(child, child);
int status;
printf("CHILD's PID (From Parent Perspective) ::: [ %d ]\n", child);
printf("PARENT's PID ::: %d\n", getpid());
printf("PARENT's GROUP ::: %d\n", getpgrp());
waitpid(child, &status, WUNTRACED | WCONTINUED);
}
while (1);
}
The issue was caused because the make
command that I started my program using was terminated by ctrl-z
. To fix the problem you can either:
OLD Problematic Make Command:
gcc -o program *.c && ./program
Potential Solutions:
(1) Remove the && ./program
line from the make command
(2) Compile and run your program without using make
I am unsure if there is anyway to still use start the program using make if you are hoping to keep your main program running in the case of a SIGTSTP
signal