24

I was surprised with this comment in other question:

Sending dd the USR1 signal too soon after it has started (i.e. in a bash script, the line after you started it) will in fact terminate it

Can anybody explain why?

Alois Mahdal
  • 4,440
  • Not so much an answer to your question, but try this one-liner: { dd if=/dev/zero of=/dev/null & }; kill -USR1 $!; jobs; sleep 1; jobs to reproduce the effect you're describing. – jippie May 13 '12 at 22:26

1 Answers1

46

Each signal has a "default disposition" -- what a process does by default when it receives that signal. There's a table in the signal(7) man page listing them:

Signal     Value     Action   Comment
──────────────────────────────────────────────────────────────────────
...
SIGUSR1   30,10,16    Term    User-defined signal 1
SIGUSR2   31,12,17    Term    User-defined signal 2

SIGUSR1 and SIGUSR2 both have the default action Term -- the process is terminated. dd registers a handler to intercept the signal and do something useful with it, but if you signal too quickly it hasn't had time to register that handler yet, so the default action happens instead

Michael Mrozek
  • 93,103
  • 40
  • 240
  • 233
  • 1
    I wish I could upvote twice for being made aware of this obscurity. Seeing processes die randomly after removing an explicit signal handler was disconcerting. – DeaconDesperado Mar 09 '16 at 19:39
  • 2
    Is there any practical way to control this race condition instead of just sleeping for a reasonable amount of time (~0.5-1 sec)? (I mean, beside something ludicrous like capturing and parsing strace output in a shell script…) – Adrian Günter Apr 20 '18 at 17:16
  • I had a shell script working fine. But suddenly stop working because of likely!: I had hyperthreding on now off. The subprocess sending kill -s SIGUSR1 $PARENT_PID gets too fast now?. The grand parent thinks the parent is terminated normally, but the parent is still executing the loop. This is a good posting. I have been spending most of the day trying to figure this out. – Kemin Zhou Nov 26 '18 at 23:02
  • 1
    @AdrianGünter "Is there any practical way to control this race condition …?" – Run trap '' USR1 in the (sub)shell that is going to run dd. Compare trap - USR1; dd if=/dev/zero of=/dev/null & kill -s USR1 "$!"; sleep 1; kill -s USR1 "$!"; sleep 1; kill "$!" to trap '' USR1; dd if=/dev/zero of=/dev/null & kill -s USR1 "$!"; sleep 1; kill -s USR1 "$!"; sleep 1; kill "$!". – Kamil Maciorowski Jun 29 '23 at 10:38