Implementing infinite wait in shell scripting

前端 未结 7 579
独厮守ぢ
独厮守ぢ 2021-02-05 04:30

This may sound trivial, but I\'m pretty sure this question hasn\'t been asked, or at least I can\'t find it.

I\'m looking for a way to construct an infinite wait

相关标签:
7条回答
  • 2021-02-05 05:10

    Why do not you use sleep forever? This is designed to forever block.

    0 讨论(0)
  • 2021-02-05 05:11

    you can use a named pipe for your read:

    mkfifo /tmp/mypipe
    #or mknode /tmp/mypipe p
    

    if you later want to send different arbitrary "signals" to the pipe, the read can be use in combination with a case statement to take appropriate actions (even useful ones)

    while read SIGNAL; do
        case "$SIGNAL" in
            *EXIT*)break;;
            *)echo "signal  $SIGNAL  is unsupported" >/dev/stderr;;
        esac
    done < /tmp/mypipe
    
    0 讨论(0)
  • 2021-02-05 05:12
    #!/bin/sh
    at_term() {
      echo 'Terminated.'
      exit 0
    }
    trap at_term TERM
    echo $$
    while true; do
      sleep 20 &
      wait $!
    done
    
    0 讨论(0)
  • 2021-02-05 05:14

    What's wrong with your 2nd option but forcing it to read from stdin ? (Requires bash)

    while true; do
      read
    done < /dev/stdin
    

    From man bash

    Bash handles several filenames specially when they are used in redirections, as described in the following table:

              /dev/stdin
                     File descriptor 0 is duplicated.
    
    0 讨论(0)
  • 2021-02-05 05:20

    SIGTERM sent to a process is delivered by the kernel to the process whether it is sleeping or not.

    Try experimenting, maybe like this (bash example)

    sleep 20 &
    kill $! && fg
    
    0 讨论(0)
  • 2021-02-05 05:26

    Here's a solution without a loop:

    #!/usr/local/bin/dash
    
    echo $$
    
    # -$$: kill process group (parent and children)
    #trap 'trap - TERM; kill 0' TERM
    #trap 'trap - INT TERM; kill 0' INT TERM
    
    trap 'trap - TERM; kill -s TERM -- -$$' TERM
    
    tail -f /dev/null & wait
    
    exit 0
    
    0 讨论(0)
提交回复
热议问题