attach to process by pid?

Nobody nobody at nowhere.com
Thu Mar 10 21:18:06 EST 2011


On Thu, 10 Mar 2011 23:55:51 +0100, Alexander Kapps wrote:

>>> I think he wants to attach to another process's stdin/stdout and
>>> read/write from/to them.
>>> I don't know if this is possible but it would be a great addition for
>>> psutil.
>>
>> It's not even a meaningful concept, let alone possible.
> 
> Unless I misunderstand something,

You do ...

> it is possible (at least on Linux):
> 
> Two terminal windows:
> 
> 1:
> alex at frittenbude:~$ grep foobar
> 
> 2:
> alex at frittenbude:~$ ps ax|grep 'grep foobar'
> 13075 pts/4    S+     0:00 grep --color=auto grep foobar
> alex at frittenbude:~$ echo foobar > /proc/13075/fd/0

The /proc/<pid>/fd/<n> pseudo-files are just aliases for whatever "object"
(file, device, socket, ...) is attached to that descriptor. Writing to the
pseudo-file writes to the file, not to the descriptor. E.g.:

	$ > foo.txt
	$ sleep 100 < foo.txt &
	[1] 17380
	$ cat foo.txt
	$ echo hello > /proc/17380/fd/0
	$ cat foo.txt
	hello

Similarly, if the process' standard input is a terminal, writing to
/proc/<pid>/fd/0 will write to the terminal. It will not cause the data to
appear on the process' standard input.

There are a few situations where it will work (for some values of "work").

E.g. in the case where standard input is a file, writing to .../fd/0 will
write to the file. If you open .../fd/0 in append mode (or if the process
hasn't started reading it yet), the next time the process reads from the
file, it will read the data which was just written. Of course, this
assumes that you have write permission on the file and don't mind
modifying it (and, if you *don't* use append mode, overwriting it).

Also, if .../fd/0 is a pipe (named or otherwise), opening it for write
will get you the write end of the pipe, while the process' standard input
has the read end. This is the one case which will usually work as expected.

Essentially, you can read or write files (pipes, devices, etc). You can't
read or write to another process' descriptors.

In the case of a pipe, writing to the pipe itself Does The Right Thing. In
some other cases, you could write to some other object to get the desired
result; e.g. if the process' stdin is a pseudo-terminal, writing to the
corresponding master device would cause the data to appear on the process'
stdin (but I don't know if that's actually possible with Unix98-style
ptys).

In other cases, there's no way to achieve the desired result. E.g. if the
process' stdin is a physical terminal, the only way to cause the
device to generate data is by pressing keys on the terminal.




More information about the Python-list mailing list