Home > Net >  Why subprocess of a script disappears after signal is sent?
Why subprocess of a script disappears after signal is sent?

Time:02-04

I have a script (flexblocks) that prints a status of my system every second. So that I can pipe it into lemonbar. It looks like this:

#!/bin/sh

main() {
  while true; do
    sleep "1s" // This

    // ...

    printf '%s\n' "some status here"
  done
}

refresh() {
  unset "$@"
}

trap "refresh node" "USR1"
trap "refresh pmix song" "USR2"
main

As you can see, I trapped two custom user signals before the main function is invoked. These are called from other scripts to refresh the bar. So in the refresh function I unset the given variables to load them again and I also want to kill the sleep process mentioned as // This in the code above.

However, the sleep process suddenly disappears when the signal is sent. Any ideas?


This is the output of pstree "$(pidof -x flexblocks)" when I run it outside of the script:

flexblocks───sleep

And it is the output of the same commnad within the function of signal USR signals:

flexblocks---pstree

pgrep does not find any process named sleep when running inside the refresh function.

CodePudding user response:

Trapped shell signals are not delivered until after foreground commands — a command the shell is waiting to exit before it advances to its next instruction – are completed. (The wait builtin is an exception to this.) (POSIX.1-2008 Shell and Utilities §2.11) Thus, your sleep has exited by the time the USR1 or USR2 trap is sprung.

For example:

$ cat zzz.sh
#! /bin/sh

trap 'echo USR1 $(date)' USR1

date
sleep 15
date

$ sh zzz.sh &
[1] 7689
Thu Feb  3 11:52:18 CST 2022

$ kill -USR1 7689

$
USR1 Thu Feb 3 11:52:33 CST 2022
Thu Feb  3 11:52:33 CST 2022

[1]   Done                    sh zzz.sh
  •  Tags:  
  • Related