Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can we have more file descriptors other than the usual stdin/stdout/stderr (0, 1, 2) ones?

Tags:

bash

shell

unix

Can we assign to any file a file descriptor number actually?

like image 374
user1155119 Avatar asked Jan 18 '12 00:01

user1155119


2 Answers

Yes you can. But it is up to the program in question if it does something with it.

$ cat fd.c 
int main()
{
    write(5,"test\n",5);
}
$ gcc fd.c
$ ./a.out 5> file
$ cat file
test
$ ./a.out 5>&1
test
$ ./a.out 
$ 

In that last case, the output to fd 5 vanished.

openssl uses this to allow passphrases and such to be passed to the process without using regular argv (which may expose them).

update the input case:

$ cat fd_in.c 
int main()
{
    unsigned char buf[16];
    write(5,buf,read(6,buf,16));
}
$ gcc fd_in.c 
$ ./a.out 6< file 5>&1
test

(file contained test\n from the previous example)

like image 174
mvds Avatar answered Oct 16 '22 09:10

mvds


Yes, in bash you can use file descriptor for reading and/or writing and can use any number. However, since 0, 1 and 2 is used for STDIN, STDOUT and STDERR, we avoid those. Also, numbers greater than 9 are used internally so we tend to avoid those as well.

This is how we can open a file descriptor to do the following:

Read:

fd<source

Write:

fd>source

Read/Write:

fd<>source

where fd is a digit that describes file descriptor and source can be either a file or even another file descriptor (though you would add & before it).

If you are using exec for file descriptors then that allows the changes to take effect in the current shell. Otherwise they are local to function or loop.

Example 1 -

Following use of fd will be local to while loop and you cannot use it outside:

while read line <&3; do 
    echo $line; 
done 3<test.file

Example 2 -

Following use of fd will be visible in the current shell

exec 3<test.file
while read line <&3; do 
    echo $line; 
done
like image 4
jaypal singh Avatar answered Oct 16 '22 08:10

jaypal singh