I read about add signal() function in the signal handler function can over write the default behaviour:
#include <stdio.h>
#include <signal.h>
#include <unistd.h>
void signalHandler();
int main(void) {
signal(SIGUSR1, signalHandler);
sleep(60);
printf("I wake up");
return 0;
}
void signalHandler() {
signal(SIGUSR1, signalHandler);// I add this line to overwrite the default behaviour
printf("I received the signal");
}
And I trigger it with another process
#include <stdio.h>
#include <signal.h>
#include <stdlib.h>
int main(int argc, char *argv[]) {
kill(5061, SIGUSR1); // 5061 is the receiver pid, kill(argv[1], SIGUSR1) doesn't working, when I get 5061 as parameter
puts("send the signal ");
return 0;
}
The receiver process wake up as soon as it receiver the SIGUSR1 signal. How can I make the receiver continue sleep even when it receive the signal from other process?
BTW why kill(5061, SIGUSR1); 5061 is the receiver pid, kill(argv[1], SIGUSR1) doesn’t work, when I get 5061 as parameter?
Your question (why
kill(argv[1], SIGUSR1)does not work) actually is not related to signals, but to basic C programming. Please compile withgcc -Wall -g(i.e. all warnings and debugging information) on Linux, and improve your code till no warning is given.Please read carefully the kill(2) man page (on Linux, after installing packages like
manpagesandmanpages-devandman-dbon Ubuntu or Debian, you can typeman 2 killto read it on your computer). Read also carefully signal(2) and signal(7) man pages. Read these man pages several times.Then, understand that the kill syscall is declared as
and since
pid_tis some integral type, you need to convertargv[1](which is a string, i.e. achar*) to some integer (andkill(argv[1], SIGUSR1)should not even compile without errors, sinceargv[1]is not some integer but a string). So please use:The man page says also that you should use
signal(SIGUSR1, SIG_DFL)to restore the default behavior, andsignal(SIGUSR1, SIG_IGN)to ignore that signal.Of course, you should better use sigaction(2) as the man page of
signal(2)tells you.At last, please take the habit of reading man pages and spend hours to read good books like Advanced Linux Programming and Advanced Unix Programming. They explain things much better than we can explain in a few minutes. If you are not familiar with C programming, read also some good book on it.