1 of 30

1

CS644 week 8:

Signals

2 of 30

Signal basics

2

3 of 30

Signals – asynchronous alerts,

sent by OS or by another process

3

Signal basics

4 of 30

SIGTERM – requests termination

SIGKILL – forces termination

SIGCHLD – notifies parent of child's exit

4

Signal basics

5 of 30

Every signal has a disposition:

ignore, default, or call handler

5

Signal basics

6 of 30

Signals can be (temporarily) masked

6

Signal basics

7 of 30

Masking – signals received are kept pending

Ignoring – signals received are discarded

7

Signal basics

8 of 30

Syscalls

8

9 of 30

int kill(

pid_t pid,

int sig,

)

9

Syscalls

10 of 30

int sigaction(

int signum,

struct sigaction* act,

struct sigaction* old,

)

10

Syscalls

11 of 30

struct sigaction {

void (*sa_handler)(int);

sigset_t sa_mask;

int sa_flags;

}

11

Syscalls

12 of 30

int sigprocmask(

int how,

sigset_t* set,

sigset_t* old,

)

12

Syscalls

13 of 30

sigprocmask(

SIG_BLOCK, ...);

sigprocmask(

SIG_UNBLOCK, ...);

sigprocmask(

SIG_SETMASK, ...);

13

Syscalls

14 of 30

int sigemptyset(sigset_t*);

int sigfillset(sigset_t*);

int sigaddset(

sigset_t*, int signo);

int sigdelset(

sigset_t*, int signo);

14

Syscalls

15 of 30

int pause()

int sigwait(

sigset* set,

int* sig,

)

15

Syscalls

16 of 30

Signals are hard

16

17 of 30

Signals are concurrent and preemptive

17

Signal are hard

18 of 30

Many functions are not safe to call inside a signal handler

18

Signal are hard

19 of 30

pause is perilous – missed-wait problem

19

Signal are hard

20 of 30

Signals can interrupt syscalls (EINTR)

20

Signal are hard

21 of 30

Signals and multithreading

21

22 of 30

Dispositions are per-process, masks are per-thread

22

Signal and multithreading

23 of 30

A signal is delivered to a particular thread, not all of them

23

Signal and multithreading

24 of 30

Use pthread_sigmask instead of sigprocmask

24

Signal and multithreading

25 of 30

What should I do?

25

26 of 30

Is default behavior OK?

26

What should I do?

27 of 30

Graceful shutdown: catch SIGTERM, set flag or self-pipe trick, handle in main loop

27

What should I do?

28 of 30

Need something more complicated? Be careful!

28

What should I do?

29 of 30

In-class exercises

29

30 of 30

Let's catch a signal!

30

In-class exercises