signal (unreliable)

Header File

#include <signal.h>

Function Prototype

void (*signal(int signo, void (*func)(int)))(int);
  • signo: the signal that we receive
  • func: the function address we want to use as signal handler when receiving signo
  • The return value of this system call is the address of the previous handler

func

  • SIG_IGN:將其設為 ignore
  • SIG_DFL:將其設為 default actionj

Function

我們可以用 signal system call 來設定 signal handler,但值得注意的是,用 signal system call 設定的 signal handler 會在第一次使用之後變回 default action

Problem & Solution

Problem

我們在沒有改變 signal 的狀況下無法知道目前的 disposition 是什麼

Solution

int sig_int();
if (signal(SIGINT, SIG_IGN) != SIG_IGN)
	signal(SIGINT, sig_int);

當我們用 background process 時 OS 會讓 SIGINT 的 disposition 變成 ignore,這樣我們在 terminal CTRL-C 才不會意外關掉 background process

上面的程式保證我們在 SIGINT disposition 在非 ignore 的情況下才會改變 signal handler