Last active
August 18, 2017 16:00
-
-
Save CMCDragonkai/6c3716fa6445f7ca448d to your computer and use it in GitHub Desktop.
CLI: Get a free unused file descriptor
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env sh | |
# this works in sh, ash, bash, zsh | |
# and works in Linux and Cygwin and Busybox | |
# probably works in Mac too | |
# remember process subtitution is not POSIX | |
# comm would normally require --nocheck-order but busybox comm doesn't, so we just send error messages to /dev/null | |
# min_fd -> max_fd -> number_of_fds_to_return | |
get_free_fd () { | |
seq "$1" "$2" > /tmp/free_fd | |
echo -n /proc/$$/fd/[0-9]* | tr ' ' '\0' | xargs -0 -I '{}' basename '{}' | sort -n > /tmp/used_fd | |
free_fd="$(comm -23 /tmp/free_fd /tmp/used_fd 2>/dev/null | head -n "$3")" | |
rm /tmp/free_fd && rm /tmp/used_fd | |
printf "$free_fd" | |
[ -n "$free_fd" ] && return 0 || return 1 | |
} | |
# use it like: | |
get_free_fd 0 $(ulimit -n) 1 | |
# it will return a file descriptor or return nothing at all | |
# you can test for an available file descriptor using `test -n` | |
# if you're in bash 4.0 or latest ZSH, there's an easier ways to do this | |
# see: http://stackoverflow.com/a/17030546/582917 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment