ANSI C has a library function raise() for sending a signal to the program that contains this raise() call. The following is the function prototype:
If this function is executed successfully, the signal specified in sig is generated. If the program has a signal handler, this signal will be processed by the that signal handler; otherwise, this signal will be handled by the default way. If the call is unsuccessful, raise() returns a non-zero value.int raise(int sig)
Note that function raise() can only send a signal to the program that contains it. raise() cannot send a signal to other processes. To send a signal to other processes, the system call kill() should be used. Click here to learn more about kill().
#include <stdio.h>
#include <signal.h>
long prev_fact, i;
void SIGhandler(int);
void SIGhandler(int sig)
{
printf("\nReceived a SIGUSR1. The answer is %ld! = %ld\n",
i-1, prev_fact);
exit(0);
}
void main(void)
{
long fact;
printf("Factorial Computation:\n\n");
signal(SIGUSR1, SIGhandler);
for (prev_fact = i = 1; ; i++, prev_fact = fact) {
fact = prev_fact * i;
if (fact < 0)
raise(SIGUSR1);
else if (i % 3 == 0)
printf(" %ld! = %ld\n", i, fact);
}
}