Saturday, October 11, 2014

Unix Prog: signal function

1. signal system call

System Definition:
 ubuntu@ip-172-31-23-227:~$ less /usr/include/signal.h  
 ......  
 /* Type of a signal handler. */  
 typedef void (*__sighandler_t) (int);  
 ......  
 /* Set the handler for the signal SIG to HANDLER, returning the old  
   handler, or SIG_ERR on error.  
   By default `signal' has the BSD semantic. */  
 __BEGIN_NAMESPACE_STD  
 #ifdef __USE_BSD  
 extern __sighandler_t signal (int __sig, __sighandler_t __handler)  
    __THROW;  
 #else  
 ......  

 ubuntu@ip-172-31-23-227:~$ less /usr/include/asm-generic/signal-defs.h  
 ......  
 #define SIG_DFL ((__sighandler_t)0)   /* default signal handling */  
 #define SIG_IGN ((__sighandler_t)1)   /* ignore signal */  
 #define SIG_ERR ((__sighandler_t)-1)  /* error return from signal */  
 ......  

The second argument of signal system call, could be:
1) SIG_DFL: then the specified signal will let system run default action
2) SIG_IGN: then the specified signal will be ignored at the current process
3) function address: the function handler used to catch the signal.

If the returning previous handler is SIG_ERR, then some error happens.

2. Example:
signal.c:
 #include<stdio.h>  
 #include<stdlib.h>  
 #include<signal.h>  
   
 static void sig_usr(int signo)  
 {  
  if(signo == SIGUSR1)  
   printf("received SIGUSR1\n");  
  else if (signo == SIGUSR2)  
   printf("received SIGUSR2\n");  
  else  
   printf("received signal %d\n", signo);  
 }  
   
 int main(int argc, char* argv[])  
 {  
  if(signal(SIGUSR1, sig_usr) == SIG_ERR) {  
   printf("Can't catch the signal!\n");  
   exit(1);  
  }  
  if(signal(SIGUSR2, sig_usr) == SIG_ERR) {  
   printf("Can't catch the signal!\n");  
   exit(2);  
  }  
  for(;;)  
   pause();  
 }  

shell:
We use signal system to setup the system call for SIGUSR1 and SIGUSR2. After running the signal.out at the background, we send USR1 and USR2 signal to this process.
 ubuntu@ip-172-31-23-227:~$ ./signal.out &  
 [1] 20018  
 ubuntu@ip-172-31-23-227:~$ kill -USR1 20018  
 ubuntu@ip-172-31-23-227:~$ received SIGUSR1  
   
 ubuntu@ip-172-31-23-227:~$ kill -USR2 20018  
 ubuntu@ip-172-31-23-227:~$ received SIGUSR2  
   

3. Program Startup
1) If a program is executed by its calling process with exec command. Then all signals are set to default disposition unless the calling process ignore the signal. If the calling process setup some signal handlers, after running "exec" system call, all these signal handlers are deserted and signals are converted to "default action"

2) If we run a program in the background, the system will automatically ignore the interrupt signals and quit signals. Then even if we type any character, it won't be caught by background processes.

3) If a process fork a child process, then the child process will inherit all the parent's signal dispositions.

No comments:

Post a Comment