您的位置:首页 > 其它

使用信号实现超时

2008-10-30 16:57 337 查看
信号是软件中断,能够提供一种处理异步事件的方法。
这些信号被定义在signal.h中,列表如下:

#define SIGHUP 1 /* Hangup (POSIX). */
#define SIGINT 2 /* Interrupt (ANSI). */
#define SIGQUIT 3 /* Quit (POSIX). */
#define SIGILL 4 /* Illegal instruction (ANSI). */
#define SIGTRAP 5 /* Trace trap (POSIX). */
#define SIGABRT 6 /* Abort (ANSI). */
#define SIGIOT 6 /* IOT trap (4.2 BSD). */
#define SIGBUS 7 /* BUS error (4.2 BSD). */
#define SIGFPE 8 /* Floating-point exception (ANSI). */
#define SIGKILL 9 /* Kill, unblockable (POSIX). */
#define SIGUSR1 10 /* User-defined signal 1 (POSIX). */
#define SIGSEGV 11 /* Segmentation violation (ANSI). */
#define SIGUSR2 12 /* User-defined signal 2 (POSIX). */
#define SIGPIPE 13 /* Broken pipe (POSIX). */
#define SIGALRM 14 /* Alarm clock (POSIX). */
#define SIGTERM 15 /* Termination (ANSI). */
#define SIGSTKFLT 16 /* Stack fault. */
#define SIGCLD SIGCHLD /* Same as SIGCHLD (System V). */
#define SIGCHLD 17 /* Child status has changed (POSIX). */
#define SIGCONT 18 /* Continue (POSIX). */
#define SIGSTOP 19 /* Stop, unblockable (POSIX). */
#define SIGTSTP 20 /* Keyboard stop (POSIX). */
#define SIGTTIN 21 /* Background read from tty (POSIX). */
#define SIGTTOU 22 /* Background write to tty (POSIX). */
#define SIGURG 23 /* Urgent condition on socket (4.2 BSD). */
#define SIGXCPU 24 /* CPU limit exceeded (4.2 BSD). */
#define SIGXFSZ 25 /* File size limit exceeded (4.2 BSD). */
#define SIGVTALRM 26 /* Virtual alarm clock (4.2 BSD). */
#define SIGPROF 27 /* Profiling alarm clock (4.2 BSD). */
#define SIGWINCH 28 /* Window size change (4.3 BSD, Sun). */
#define SIGPOLL SIGIO /* Pollable event occurred (System V). */
#define SIGIO 29 /* I/O now possible (4.2 BSD). */
#define SIGPWR 30 /* Power failure restart (System V). */
#define SIGSYS 31 /* Bad system call. */
#define SIGUNUSED 31

其中,有一个信号是闹钟信号SIGALRM,在程序中,我们可以调用alarm函数设置一个超时数值,当超过这个值之后内核将会向该进程发送SIGALRM信号。按POSIX的说明,如果不捕获或者忽略该信号,默认的动作是终止该进程。但事实上我们一般不会使用默认的动作,而是进行自己的处理。

alarm函数的原型是 unsigned int alarm(unsigned int seconds)

它的参数seconds是超时的秒数,它有返回值。如果上一次使用了alarm函数,并且还没有到超时时间又使用了alarm函数,它会将上一次设置的seconds返回以便程序对其进行处理。

#include <sys/types.h>
#include <stdio.h>
#include <stdlib.h>
#include <signal.h>

static short int is_run = 1;

void sig_alarm(int);

int main(int argc, char *argv[])
{
if(signal(SIGALRM, sig_alarm) == SIG_ERR)
{
perror("signal()");
return 0;
}
alarm(5);
printf("process will stop after 5 seconds!/n");
while(is_run);
printf("process stop!/n");
return 0;
}

void sig_alarm(int seconds)
{
is_run = 0;
}

程序中有一个空循环,条件是is_run。而闹钟信号监听程序将is_run设置为0从而终止了该循环。其结果为:

process will stop after 5 seconds!
process stop!

其中第二句是五秒后才输出的。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐