Linux教程網
1.簡單的信號處理程序
- #include <unistd.h>
- #include <stdlib.h>
- #include <stdio.h>
- #include <signal.h>
-
- static void sig_usr(int);
- typedef void Sigfunc(int);
- Sigfunc *signal(int,Sigfunc *);
-
- int main(int argc,char **argv)
- {
- if(signal(SIGUSR1,sig_usr) == SIG_ERR){
- fprintf(stderr,"Error!\n");
- exit(-1);
- }
- if(signal(SIGUSR2,sig_usr) == SIG_ERR){
- fprintf(stderr,"Error!\n");
- exit(-1);
- }
-
- while(1)
- pause();
- }
-
- static void sig_usr(int signo)
- {
- if(signo == SIGUSR1)
- printf("received SIGUSR1!\n");
- if(signo == SIGUSR2)
- printf("received SIGUSR2!\n");
- else
- printf("received signal %d\n",signo);
- }
後台執行,.然後使用kill命令來發送信號。
- <strong>$ ./a.out &</strong>
- [1] 7216
- <strong>$ kill -USR1 7216
- </strong>received SIGUSR1
- <strong>$ kill -USR2 7216</strong>
- received SIGUSR2
- <strong>$ kill 7216
- </strong>[1]+ Terminated ./a.out
2.調用不可重入函數的示例程序
- #include <unistd.h>
- #include <stdlib.h>
- #include <stdio.h>
- #include <signal.h>
-
- typedef void Sigfunc(int);
- Sigfunc *signal(int,Sigfunc *);
-
- static void my_alarm(int signo)
- {
- struct passwd *rootptr;
-
- printf("in signal handle\n");
- if((rootptr = getpwnam("root")) == NULL){
- printf("error!\n");
- exit(-1);
- }
- alarm(1);
- }
- int main(int argc,char **argv)
- {
- struct passwd *ptr;
-
- signal(SIGALRM,my_alarm);
- alarm(1);
- for(;;){
- if((ptr = getpwnam("leon")) == NULL)
- err_sys("getpwnam error");
- if(strcmp(ptr->pw_name,"leon") != 0)
- printf("return value corrupted!,pw_name = %s\n",ptr->pw_name);
- }
- }
Copyright ©
Linux教程網 All Rights Reserved