Interrupt sleep in bash with a signal trap

后端 未结 3 1097
无人及你
无人及你 2020-12-04 18:23

I\'m trying to catch the SIGUSR1 signal in a bash script that is sleeping via the sleep command:

#!/bin/bash

trap \'echo \"Caught          


        
相关标签:
3条回答
  • 2020-12-04 18:41
    #!/bin/bash
    
    trap 'echo "Caught SIGUSR1"' SIGUSR1
    
    echo "Sleeping.  Pid=$$"
    while :
    do
       sleep 10 &
       wait $!
       echo "Sleep over"
    done
    
    0 讨论(0)
  • 2020-12-04 18:42

    Remark that

    sleep infinity &
    wait
    

    puts the sleep in background, and stops the wait with the signal. This leaves an infinite sleep behind on every signal !

    Replace the sleep and wait with

    read
    

    and you will be fine.

    0 讨论(0)
  • 2020-12-04 18:44

    Just a point about the wait after the sleep because I've just made this error in my script:

    You should use wait $! instead of wait if, inside your script, you already launched other processes in background

    For example, the wait inside the next snippet of code will wait for the termination of both process_1 and sleep 10:

    process_1 &
      ...
    sleep 10 &
    wait  
    

    If you use, instead of wait, wait $! your script will wait only for sleep 10, because $! means PID of last backgrounded process.

    0 讨论(0)
提交回复
热议问题