Вывод в файл с использованием файлового дескриптора

690
markovuksanovic

Мне было интересно, можно ли перенаправить вывод одного процесса (в OS X / Linux) на другой процесс, если я знаю fd другого процесса. Например:

Я открываю файл с помощью Vim: vim /tmp/test. Это открывает файл, и когда я использую, lsof | grep testчтобы узнать дескриптор файла, я получаю:

vim 18689 user 4u REG 1,2 12288 2675530 /private/tmp/.test.swp 

Он говорит мне, что FD 4, и что он открыт для записи и чтения.

Есть ли способ, которым я могу теперь перенаправить вывод другого процесса в этот дескриптор файла (например, echo 'test'> & 4 - это не работает, но вы поняли идею)?

4

1 ответ на вопрос

4
akira

Each process has it's own FD - table (see http://en.wikipedia.org/wiki/File_descriptor ), otherwise process A would have to communicate with process B about the filedescriptors (and not only with B but also with all the other processes on the machine). So, just knowing the (internal) FD is not enough, you need to know where this FD points to:

$> ls /proc/2964/fd total 0 lrwx------ 1 user group 64 Okt 6 15:09 0 -> /dev/pts/1 lrwx------ 1 user group 64 Okt 6 15:09 1 -> /dev/pts/1 lrwx------ 1 user group 64 Okt 6 15:09 2 -> /dev/pts/1 lrwx------ 1 user group 64 Okt 6 15:09 3 -> [eventfd] lrwx------ 1 user group 64 Okt 6 15:09 4 -> socket:[1116342098] l-wx------ 1 user group 64 Okt 6 15:09 5 -> /home/user/.irssi/logs/freenode/#channel.2014-10.log lrwx------ 1 user group 64 Okt 6 15:09 6 -> [eventfd] l-wx------ 1 user group 64 Okt 7 19:09 9 -> /home/user/.irssi/away.log 

As you can see, there are some FD open in the irc-client I use (irssi), stdin is read from the file /dev/pts/1. Given that I have the permissions to write to that file I am able to pipe stuff into that file:

$> echo "/names" >> /dev/pts/1 

And at least something will happen. So, you can redirect output of one program into another allthough that might lead to strange issues.

Похожие вопросы