The fdreserve program
fdreserve updates the environment with file descriptors that are guaranteed safe to use, then executes a program.
Interface
fdreserve n prog...
- fdreserve tries to reserve n file descriptors.
- fdreserve sets the FD0, FD1, ..., FDn-1 environment variables: each FDi contains a valid file descriptor, that can be safely opened.
- fdreserve then execs into prog with its arguments.
Common use
fdreserve can be used when you do not want to hardcode file descriptors in your scripts. For instance, to create a pipe, you could use:
#!/command/execlineb
fdreserve 2
multisubstitute
{
importas fdr FD0
importas fdw FD1
}
piperw $fdr $fdw
prog...
Warning: fdreserve does not allocate descriptors, it merely returns descriptors that are free at the time it is run. A program like
#!/command/execlineb
fdreserve 3
multisubstitute
{
importas fdr FD0
importas fdw FD1
}
piperw $fdr $fdw
fdreserve 1
multisubstitute
{
importas oldfd FD2
importas newfd FD0
}
prog...
may fail, because oldfd and newfd may be the same. To avoid that, you should make sure that all descriptors returned by fdreserve are actually allocated before calling fdreserve again. (Thanks to Paul Jarc for having spotted that case.)
