logo

当前栏目:社区首页->软件开发->自由软件与linux 转到:在该栏目发表文章社区后台管理搜索
Linux程式设计- 3.signals
作者: imac 日期: 08-03-29, 02:01
信号处理

MegaEntry 网络社区与信息交流平台!

-------------------------------------------------------------------------信号处理概说  送出信号  接收信号  信号的处理  任务控制  -------------------------------------------------------------------------POSIX IPC  reliable/unreliable  reentrant  pending  sending signals  catching signals  manipulating 

文章版权归原作者所有! (www.MegaEntry.com)

signal definitions  -------------------------------------------------------------------------信号singals 信号的处理可以用一大章来写,涉及的层面也会深入整个作业系统中,我并不打算这样做,因为您可能会越搞越迷糊。这里我只告诉您如何接上信号,在实用的层面上,这样便很够用了。您可以先利用这些基本的技巧来撰写程式,等到有进一步高等应用的需要时,找一本较深入的UNIX Programming教材,专门研究signal的写法。  一般简单的signal写法如下:  void mysignal(int signo)  {    /* my signal handler */  }  void initsignal(void)  {    struct sigaction act; 

MegaEntry 网络社区与信息交流平台!

  act.sa_handler = mysignal;    act.sa_flags   = 0;    sigemptyset(&act.sa_mask);    sigaction(SIGHUP,&act,NULL);    sigaction(SIGINT,&act,NULL);    sigaction(SIGQUIT,&act,NULL);    sigaction(SIGILL,&act,NULL);    sigaction(SIGTERM,&act,NULL);  }     例一: lock.c 在fork的例三中提到,在daemon被杀掉时,需要在离开前,将/var/run/lock.pid删除。这里我们可以利用signal来处理这件事。  #include   #include   #include  

文章版权归原作者所有! (www.MegaEntry.com)

#include   #define LOCK_FILE  "/var/run/lock.pid "  void quit(int signo)  {    printf( "Receive signal %d ",signo);    unlink(LOCK_FILE);    exit(1);  }  void main(void)  {    FILE *fp;    pid_t pid;    struct sigaction act; 

文章版权归原作者所有! (www.MegaEntry.com)

  if (access(LOCK_FILE,R_OK)==0) {      printf( "Existing a copy of this daemon! ");      exit(1);    }    pid = fork();    if (pid>0) {      printf( "daemon on duty! ");      fp = fopen(LOCK_FILE, "wt ");      fprintf(fp, "%d ",pid);      fclose(fp);    } else      exit(0);  if (pid<0) { 

MegaEntry 网络社区与信息交流平台!

    printf( "Can 't fork! ");      exit(-1);    }    act.sa_handler = quit;    act.sa_flags   = 0;    sigemptyset(&act.sa_mask);    sigaction(SIGTERM,&act,NULL);    sigaction(SIGHUP,&act,NULL);    sigaction(SIGINT,&act,NULL);    sigaction(SIGQUIT,&act,NULL);    sigaction(SIGUSR1,&act,NULL);    sigaction(SIGUSR2,&act,NULL);    for (;;) {      sleep(3); 

文章版权归原作者所有! (www.MegaEntry.com)

  }  }  编译: gcc -o ex1 lock.c  执行 ./ex1  daemon on duty!  送信号 我们先找出该守护神程式的pid  PID=`cat /var/run/lock.pid`  接下来利用kill来送信号  kill $PID 

文章版权归原作者所有! (www.MegaEntry.com)

Receive signal 15  程式将会结束,并且/var/run/lock.pid将会被删除掉,以便下一次daemon再启动。注意到如果quit函数内,没有放exit(),程式将永远杀不掉。  接下来送一些其它的信号试试看。  ./ex1  PID=`cat /var/run/lock.pid`  kill -HUP $PID  Receive signal 1  您可以自行试试  kill -INT $PID  kill -QUIT $PID  kill -ILL $PID 

文章版权归原作者所有! (www.MegaEntry.com)

.  .  .  等等这些信号,看看他们的结果如何。  信号的定义 在/usr/include/signum.h中有各种信号的定义  #define SIGHUP          1 &nb 

上一篇:Linux程式设计- 4.socket下一篇:Linux程式设计- 2.fork, pthread, and ...

回复
标题: 

强烈建议采用IE 6.0或以上的浏览器