Reputation: 33
I've googled far and wide and have come across no CLEAR instructions on how to use a user-defined signal (SIGUSR1/SIGUSR2).
Context: I am trying to send a signal within the running process so that once the signal is sent, the signal handler will print a statement to tell the user that the signal has been caught. I have tried to use a signal handler as shown below.
void signalHandler(int signalNum) {
if (signalNum == SIGUSR1) {
printf("Caught SIGUSR1 signal.\n");
}
}
/* Call in main as follows */
signal(SIGUSR1, signalHandler);
Now from what I understand, it is possible to raise a signal within a process by using the raise() function which I have tried (I'm trying to do the following WITHOUT forking or using subsequent child/parent processses). When taking the approach that I have shown above, the program never executes any of the code inside the signal handler function, even if it is a print statement before the if statement.
Following this, I have also tried:
signalHandler(raise(SIGUSR1));
Forgive if my approaches are forbidden, I come from a Python background. Thanks!
EDIT: I need the program to autonomously signal itself, catch the signal, print the message THEN cease executing. No use of the CLI.
Upvotes: 3
Views: 21555
Reputation: 9213
You can send signals to a process using the kill
command. The list of all the signals is available on the signal
man-page.
You can identify the pid
of your process using the ps
command and send the signal as
kill -10 <pid>
This is the method if you want to send the signal externally from the terminal. If you want the process itself to send the signal (or raise the signal), you can use raise
as -
raise(SIGUSR1);
The demo for the same is here.
If you want to send the signal from another process programmatically you can use kill
as -
kill(pid, SIGUSR1);
Upvotes: 3