訊號是一種軟體中斷,程式收到訊號時,就會調用相應的處理函數(如果有註冊)。
void (*signal(int signum,void(* handler)(int)))(int); -- 設定訊號處理方式訊號處理函數原型void foo(int arg); 系統定義的訊號有:/* Signals. */#define SIGHUP1/* Hangup (POSIX). */#define SIGINT2/* Interrupt (ANSI). */#define SIGQUIT3/* Quit (POSIX). */#define SIGILL4/* Illegal instruction (ANSI). */#define SIGTRAP5/* Trace trap (POSIX). */#define SIGABRT6/* Abort (ANSI). */#define SIGIOT6/* IOT trap (4.2 BSD). */#define SIGBUS7/* BUS error (4.2 BSD). */#define SIGFPE8/* Floating-point exception (ANSI). */#define SIGKILL9/* Kill, unblockable (POSIX). */#define SIGUSR110/* User-defined signal 1 (POSIX). */#define SIGSEGV11/* Segmentation violation (ANSI). */#define SIGUSR212/* User-defined signal 2 (POSIX). */#define SIGPIPE13/* Broken pipe (POSIX). */#define SIGALRM14/* Alarm clock (POSIX). */#define SIGTERM15/* Termination (ANSI). */#define SIGSTKFLT16/* Stack fault. */#define SIGCLDSIGCHLD/* Same as SIGCHLD (System V). */#define SIGCHLD17/* Child status has changed (POSIX). */#define SIGCONT18/* Continue (POSIX). */#define SIGSTOP19/* Stop, unblockable (POSIX). */#define SIGTSTP20/* Keyboard stop (POSIX). */#define SIGTTIN21/* Background read from tty (POSIX). */#define SIGTTOU22/* Background write to tty (POSIX). */#define SIGURG23/* Urgent condition on socket (4.2 BSD). */#define SIGXCPU24/* CPU limit exceeded (4.2 BSD). */#define SIGXFSZ25/* File size limit exceeded (4.2 BSD). */#define SIGVTALRM26/* Virtual alarm clock (4.2 BSD). */#define SIGPROF27/* Profiling alarm clock (4.2 BSD). */#define SIGWINCH28/* Window size change (4.3 BSD, Sun). */#define SIGPOLLSIGIO/* Pollable event occurred (System V). */#define SIGIO29/* I/O now possible (4.2 BSD). */#define SIGPWR30/* Power failure restart (System V). */#define SIGSYS31/* Bad system call. */#define SIGUNUSED31 #define_NSIG65/* Biggest signal number + 1 (including real-time signals). */ #define SIGRTMIN (__libc_current_sigrtmin ())#define SIGRTMAX (__libc_current_sigrtmax ())
向進程發送訊號(在終端)kill -s signal pid -- signal的值是上面列表中的合法值kill -s 9 pid -- 該命令會結束指定的進程 下面的例子顯示進程接收到的訊號
#include <unistd.h>#include <stdio.h>#include <signal.h>void handler(int arg){ printf("get signal %d\n", arg); }int main(){ int i; for (i=0; i<SIGRTMAX; i++) signal(i, handler); while(1) { pause(); } return 0;}
可以用kill -s 9 pid結束它
kill也是一個可調用的APIint kill(pid_t pid,int sig); kill()可以用來送參數 sig指定的訊號給參數pid指定的進程。參數pid有幾種情況: pid>0 將訊號傳給進程識別碼為 pid的進程。 pid=0 將訊號傳給和目前進程相同進程組的所有進程 pid=-1 將訊號廣播傳送給系統內所有的進程pid<0 將訊號傳給進程組識別碼pid絕對值的所有進程