execline: the redirfd command
Keywords: execline command redirfd

execline
Software
skarnet.org

# The `redirfd` program

`redirfd` redirects a given file descriptor to a file, then executes a program.

## Interface

         redirfd [ -r | -w | -u | -a | -x ] [ -n ] [ -b ] fd file prog...

         redirfd [ -r | -w | -u | -a | -x ] [ -n ] [ -b ] [ -f ] [ -e | -E ] var file prog...

`redirfd` redirects the file descriptor number fd to file, then execs into prog....

When run with the `-v` option, the first argument is instead interpreted as an environment variable. `redirfd` opens file, stores the obtained file descriptor into environment variable var, then execs into prog....

## Options

One and only one of the -r, -w, -u, -a, or -x options must be given; the -n and -b options may be added in any case.

- `-r` : open file for reading.
- `-w` : open file for writing, truncating it if it already exists.
- `-u` : open file for reading and writing.
- `-a` : open file for appending, creating it if it doesn't exist.
- `-x` : open file for writing, creating it, failing if it already exists.
- `-n` : open file in non-blocking mode.
- `-b` : change mode of file after opening it: to non-blocking mode if the `-n` option was not given, to blocking mode if it was.
- `-f` : interpret the first argument as an environment variable, and stores the new file descriptor into that variable before execing.
- `-e` : no autoimport. This is the default.
- `-E` : autoimport. This is only useful with the `-f` option. Instead of executing prog..., execute `importas -uSi var prog...`. This substitutes var into the command line instead of putting it into the environment.

## Notes

- `redirfd -r n file prog...` is roughly equivalent to `sh -c 'exec prog... n<file'`
- `redirfd -w n file prog...` is roughly equivalent to `sh -c 'exec prog... n>file'`
- `redirfd -u n file prog...` is roughly equivalent to `sh -c 'exec prog... n<>file'`
- `redirfd -a n file prog...` is roughly equivalent to `sh -c 'exec prog... n>>file'`
- `redirfd -x n file prog...` has no portable shell equivalent.

## Special fifo handling

The `-n` and `-b` options are especially useful with named pipes.

- Opening a fifo for reading, blocking if there is no writer: `redirfd -r n fifo prog...`
- Opening a fifo for reading, with instant success even if there is no writer, and blocking at the first attempt to read from it: `redirfd -r -nb n fifo prog...`
- Opening a fifo for writing, blocking if there is no reader: `redirfd -w n fifo prog...`
- Opening a fifo for writing, with instant success even if there is no reader: `redirfd -w -nb n fifo prog...`. Warning: the first attempt to write to the fifo will raise a SIGPIPE if there is still no reader at that time. The named pipe semantics normally do not allow a fifo to be open for writing without a reading end, and you should know what you are doing if you're using `redirfd` this way.