/* * sigaction.c * Demonstrates how to use sigaction to handle signals and gather signal info. */ #define _GNU_SOURCE #include #include #include #include #include #include void sigactionFunc(int sig, siginfo_t *info, void *context) { fprintf(stdout,"Received Signal: %s\n",strsignal(sig)); fprintf(stdout,"signo: %d\n",info->si_signo); fprintf(stdout,"sig errno: %d\n",info->si_errno); fprintf(stdout,"sig code: %d\n",info->si_code); fprintf(stdout,"sig pid: %d\n",info->si_pid); fprintf(stdout,"sig uid: %d\n",info->si_uid); fprintf(stdout,"why the signal was sent: \n"); switch(info->si_code) /* look at your definitions in siginfo.h for theses codes */ { case SI_USER: fprintf(stdout,"sent by kill, sigsend\n"); break; case SI_KERNEL: fprintf(stdout,"sent by the kernel\n"); break; case SI_QUEUE: fprintf(stdout,"sent by sigqueue\n"); break; case SI_TIMER: fprintf(stdout,"sent by timer\n"); break; case SI_MESGQ: fprintf(stdout,"sent by real time mesgq state change\n"); break; case SI_ASYNCIO: fprintf(stdout,"sent by AIO completion\n"); break; case SI_SIGIO: fprintf(stdout,"sent by queued SIGIO\n"); break; case SI_TKILL: fprintf(stdout,"sent by tkill\n"); break; case SI_ASYNCNL: fprintf(stdout,"sent by asynch name lookup completion\n"); break; } fprintf(stdout,"\n\n"); fflush(stdout); } int main(int argc, char **argv) { struct sigaction act; sigset_t set; sigemptyset(&set); /* not masking any signals */ act.sa_mask=set; act.sa_sigaction=sigactionFunc; /* handle signals with the sigactionFunc */ act.sa_flags=SA_SIGINFO; /* request siginfo_t be delivered when a signal arrives */ /* apply the sigaction parameters we just set up to handle SIGHUP signals */ if(sigaction(SIGHUP,&act,NULL)!=0) /* NOTE: sigaction does not need to be reset each time a */ { /* signal is received as the signal function does */ fprintf(stdout,"failed to apply sigaction, %s\n",strerror(errno)); fflush(stdout); return -1; } /* now we send the process SIGHUP signals and see what happens */ raise(SIGHUP); /* send SIGHUP to this process using raise */ /* NOTE: on my system raise is actually implemented with */ /* the tkill function, this will be shown with the siginfo_t*/ /* parameter in the sigcatchFunc */ kill(getpid(),SIGHUP); /* send SIGHUP to this process using kill */ getchar(); return 0; }