Bash: infinite sleep (infinite blocking)

前端 未结 11 588
日久生厌
日久生厌 2020-12-04 08:27

I use startx to start X which will evaluate my .xinitrc. In my .xinitrc I start my window manager using /usr/bin/mywm. No

11条回答
  •  误落风尘
    2020-12-04 08:57

    I recently had a need to do this. I came up with the following function that will allow bash to sleep forever without calling any external program:

    snore()
    {
        local IFS
        [[ -n "${_snore_fd:-}" ]] || { exec {_snore_fd}<> <(:); } 2>/dev/null ||
        {
            # workaround for MacOS and similar systems
            local fifo
            fifo=$(mktemp -u)
            mkfifo -m 700 "$fifo"
            exec {_snore_fd}<>"$fifo"
            rm "$fifo"
        }
        read ${1:+-t "$1"} -u $_snore_fd || :
    }
    

    NOTE: I previously posted a version of this that would open and close the file descriptor each time, but I found that on some systems doing this hundreds of times a second would eventually lock up. Thus the new solution keeps the file descriptor between calls to the function. Bash will clean it up on exit anyway.

    This can be called just like /bin/sleep, and it will sleep for the requested time. Called without parameters, it will hang forever.

    snore 0.1  # sleeps for 0.1 seconds
    snore 10   # sleeps for 10 seconds
    snore      # sleeps forever
    

    There's a writeup with excessive details on my blog here

提交回复
热议问题