linux系统编程之信号(四):alarm和可重入函数


一,alarm()

在将可重入函数之前我们先来了解下alarm()函数使用:

#include <unistd.h>

unsigned int alarm(unsigned int seconds)

系统调用alarm安排内核为调用进程在指定的seconds秒后发出一个SIGALRM的信号。如果指定的参数seconds为0,则不再发送 SIGALRM信号。后一次设定将取消前一次的设定。该调用返回值为上次定时调用到发送之间剩余的时间,或者因为没有前一次定时调用而返回0。

注意,在使用时,alarm只设定为发送一次信号,如果要多次发送,就要多次使用alarm调用。

man帮助说明:


DESCRIPTION
       alarm()  arranges  for  a SIGALRM signal to be delivered to the calling
       process in seconds seconds.

       If seconds is zero, no new alarm() is scheduled.

       In any event any previously set alarm() is canceled.

RETURN VALUE
       alarm() returns the number of seconds remaining  until  any  previously
       scheduled alarm was due to be delivered, or zero if there was no previ-
       ously scheduled alarm.

示例:

#include <unistd.h><sys/stat.h><sys/wait.h><sys/types.h><fcntl.h><stdlib.h><stdio.h><errno.h><.h><signal.h>


 ERR_EXIT(m) \
    ( handler( main( argc,  * (signal(SIGALRM, handler) ==  handler(

结果:

<sys/stat.h><sys/wait.h><sys/types.h><fcntl.h><stdlib.h><stdio.h><errno.h><.h><signal.h> ERR_EXIT(m) \ ( handler( main( argc, *= {, = {, (signal(SIGALRM, handler) ===== handler(

结果:

QQ截图20130715111634

也是程序创建了一个结构体,设置一个全局变量,然后在main函数中利用两个局部变量分别给全局变量赋值,由于这个赋值操作是可被中断的,如以上每一次结构体的赋值可视为两步:

g_data.a=zeros.a;

g_data.b=zeros.b;

所以当g_data.a=one.a;做完然后被中断,跑去执行处理函数,在处理函数中调用unsafe_fun()打印全局变量值,可知结果是全局变量a值变了,b值还是之前的没来的及改变,所以出现了1,0

所以结果不确定

相关内容