Moving straight to the issue, how do I make Ctrl+z do what the title states?
My program implements a parent process which creates a single child process. Both processes will display the process ID and once the child terminates a signal is sent to the parent process and the parent signal handler will display a text stating a signal has been captured.
On the child process, on top of displaying the child's process ID, it must generate a random number between 10 and 50 every time Ctrl + z is pressed. So far I can only make the child process generate 1 random number.
Below is my code:
void main() {
int pid;
int x;
int fd[2];
const int MAXLINE=4096;
char line[MAXLINE];
pid=fork();
if (pipe(fd) < 0) {
printf("Pipe error!");
}
if (pid < 0) {
printf("Fork error!");
} else if (pid == 0) { //Child process
signal(SIGTSTP, childsignal_handler);
printf("The process id is: %i\n", getpid());
sleep(1000); //Implemented to wait for a signal
} else {
printf("The process id is: %i\n", getpid()); //Parent process
pause(); //Waits for the Child process to finish
}
}
parent signal handler:
void parentsignal_handler(int signo) { //Signal Handler for the parent process
printf("The signal in the parent process has been captured\n");
}
child signal handler:
void childsignal_handler(int signo) { //Signal Handler for the child process
signal(SIGTSTP, childsignal_handler);
printf("\nThe signal in the child process has been captured\n");
randomnumbergenerator();
pause();
}
The random number generator:
void randomnumbergenerator() { //Random number generator to run everytime Ctrl+z is pressed
//signal(SIGTSTP, childsignal_handler);
int number;
int number2 = 10;
printf("Welcome to random number generator!");
printf("\nRandom number generated = %d\n", rand() % 40 + 10);
}
PS: I have read several documentations regarding various solutions such as sigsuspend, sigprocmask,pause and so on but none of them worked so far.
below are some of the documentations i have read so far:
https://www.gnu.org/software/libc/manual/html_node/Waiting-for-a-Signal.html#Waiting-for-a-Signal https://man7.org/linux/man-pages/man2/pause.2.html
i need to implement a signal that will detect the child terminating
You don't exactly need to implement a signal; you just need to install the handler that you already have:
signal(SIGCLD, parentsignal_handler);
how do I make Ctrl+z do what the title states?
So far I can only make the child process generate 1 random number.
To prevent the parent process from being suspended (and therewith losing signal delivery), ignore the STOP signal in the parent:
signal(SIGTSTP, SIG_IGN);
And you should really pay attention to Ian Abbott's first comment and remove pause()
from the signal handler; otherwise after Ctrl-Z was pressed the program will not end. At the same time change sleep(…)
to while (sleep(…))
to keep a timed suspension instead of the unlimited pause()
.