日期:2014-05-16 浏览次数:20799 次
本文的主题是unix中的基本信号处理(signal)。
在Unix中,一个进程可以向另一个进程发送信号,接收进程再收到信号后可以根据配置做出相应反应。这也是一种通信机制。
涉及到的主要函数有:
#include<stdio.h> #include<unistd.h> #include<sys/types.h> #include<signal.h> #include<stdlib.h> void signalHandler(int signum) { printf("In signalHandler, PID=%d, signum=%d.\n", getpid(), signum); } void main(int argn, char** argv) { pid_t val_fork; int choice = -1; if(argn>1)choice = atoi(argv[1]); if((val_fork=fork())==0) { printf("In fils, before 'signal()'.\n"); if(choice==0) signal(SIGUSR1, SIG_DFL);//Invoke default action else if(choice==1) signal(SIGUSR1, SIG_IGN);//Ignore signals else signal(SIGUSR1, signalHandler);//Call user defined function. printf("In fils, after 'signal()'.\n"); printf("In fils, sleep for keeping alive\n"); sleep(5); printf("In fils, exit.\n"); exit(0); } else { printf("In pere, sleep for leaving enough time to my son.\n"); sleep(3); printf("In pere, before kill().\n"); kill(val_fork, SIGUSR1); if(choice==0) printf("In pere, OMG my son terminated himself!\n"); else if(choice==1) printf("In pere, OMG my son ignored my knife!\n"); else printf("In pere, I've just let my son execute a function!\n"); } }
#include<stdio.h> #include<unistd.h> #include<sys/types.h> #include<signal.h> #include<stdlib.h> void signalHandler(int signum, siginfo_t* siginfo, void* ucontent) { printf("In signalHandler, PID=%d, signum=%d, sending process=%d.\n", getpid(), signum, siginfo->si_pid); } void main(int argn, char** argv) { pid_t val_fork; int choice = -1; struct sigaction sa; sa.sa_sigaction=signalHandler; sa.sa_flags=SA_SIGINFO; if(argn>1)choice = atoi(argv[1]); if((val_fork=fork())==0) { printf("In fils, before 'signal()'.\n"); if(choice==0) signal(SIGUSR1, SIG_DFL);//Invoke default action else if(choice==1) signal(SIGUSR1, SIG_IGN);//Ignore signals else sigaction(SIGUSR1, &sa, NULL);//Call user defined function. printf("In fils, after 'signal()'.\n"); printf("In fils, sleep for keeping alive\n"); while(1)sleep(5); printf("In fils, exit.\n"); exit(0); } else { printf("In pere, pid=%d, sleep for leaving enough time to my son.\n", getpid()); sleep(3); printf("In pere, before kill().\n"); kill(val_fork, SIGUSR1); if(choice==0) printf("In pere, OMG my son terminated himself!\n"); else if(choice==1) printf("In pere, OMG my son ignored my knife!\n"); else printf("In pere, I've just let my son execute a function!\n"); } }