68

I'm getting acquainted with signals in C. I can't figure out what kind of signals SIGUSR1 and SIGUSR2 are and how can I trigger them. Can anyone please explain it to me?

malana
  • 5,045
  • 3
  • 28
  • 41
haunted85
  • 1,601
  • 6
  • 24
  • 40

3 Answers3

92

They are user-defined signals, so they aren't triggered by any particular action. You can explicitly send them programmatically:

#include <signal.h>

kill(pid, SIGUSR1);

where pid is the process id of the receiving process. At the receiving end, you can register a signal handler for them:

#include <signal.h>

void my_handler(int signum)
{
    if (signum == SIGUSR1)
    {
        printf("Received SIGUSR1!\n");
    }
}

signal(SIGUSR1, my_handler);
Oliver Charlesworth
  • 267,707
  • 33
  • 569
  • 680
  • 1
    Thank you for your answer. If these signals are user-defined how can they be useful? Can you give me some examples? – haunted85 May 29 '11 at 15:48
  • 11
    @haunted: They are designed for simple inter-process communication (IPC). So a child process could send it to its parent to indicate that it's completed a certain task, for instance. Obviously, much more sophisticated techniques exist for IPC (such as pipes, sockets, semaphores, etc.). – Oliver Charlesworth May 29 '11 at 15:48
  • I would avoid using them for any program-internal IPC, but the one place they can be useful is as a cheap form of user-to-program input via the kill command. – R.. GitHub STOP HELPING ICE May 29 '11 at 16:06
  • 4
    @haunted85: a concrete example would be mongodb rotating it's log files when receiving SIGUSR1: - see http://docs.mongodb.org/manual/tutorial/rotate-log-files/ – toong Feb 28 '13 at 08:46
  • 2
    @haunted85 Here is an example using `SIGUSR1` for AIO: http://linux.die.net/man/7/aio –  Apr 15 '13 at 20:57
  • 1
    QEMU uses this technique a lot to kick start a cpu model. – webbertiger Dec 16 '13 at 20:17
7

terminal 1

dd if=/dev/sda of=debian.img

terminal 2

killall -SIGUSR1 dd

go back to terminal 1

34292201+0 records in
34292200+0 records out
17557606400 bytes (18 GB) copied, 1034.7 s, 17.0 MB/s
  • 2
    this does not work with rsync btw: `rsync error: received SIGUSR1 (code 19) at main.c(1434) [sender=3.1.1]` – qwertz Feb 24 '18 at 22:08
  • Of course it doesn't have to work with `rsync`, it was just an example of an application (here: `dd`) that sets up a signal handler for SIGUSR1 for a useful function. – the busybee Aug 23 '19 at 06:08
6

They are signals that application developers use. The kernel shouldn't ever send these to a process. You can send them using kill(2) or using the utility kill(1).

If you intend to use signals for synchronization you might want to check real-time signals (there's more of them, they are queued, their delivery order is guaranteed etc).

cnicutar
  • 178,505
  • 25
  • 365
  • 392