Can we have more file descriptors than regular stdin / stdout / stderr (0, 1, 2)?

Is it possible to assign an actual file descriptor number to any file?

+6
source share
3 answers

Yes, you can. But it depends on 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 this last case, the output to fd 5 disappeared.

openssl uses this to allow phrases to pass them to a process without using regular argv (which can expose them).

update 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 contains test\n from the previous example)

+6
source

Yes, in bash you can use file descriptor to read and / or write and you can use any number. However , since 0 , 1, and 2 are used for STDIN , STDOUT, and STDERR , we avoid these. In addition, numbers greater than 9 are used internally, so we also avoid them.

Here's how we can open a file descriptor to do the following:

To read:

 fd<source 

Record:

 fd>source 

Read / write:

 fd<>source 

where fd is the number that describes the file descriptor , and the source can be either file , or even another file descriptor (although you must add & ).

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

Example 1 -

The following use of fd will be local to the while loop, and you cannot use it outside:

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

Example 2 -

The next use of fd will be visible in the current shell

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

As you noted this with bash, see AdvancedBash for the basics.

The section below this link (Example 20-2) states the following

 LOGFILE=logfile.txt exec 6>&1 # Link file descriptor #6 with stdout. # Saves stdout. exec > $LOGFILE # stdout replaced with file "logfile.txt". 

Is this what you are looking for?

+1
source

Source: https://habr.com/ru/post/906251/


All Articles