How do you stream data into the STDIN of a program

2020-02-15 03:55发布

问题:

Standard streams are associated with a program. So, suppose there is a program already running in some way (I don't care how or in what way). The goal is to create pipes to the STDIN of the program from different processes (or programs) that run either locally or remotely and stream data into it asynchronously.

Available information is (1) the host address and (2) the pid of the program only. How does one implement both cases in Python in this case?

Edit: I should have mentioned this presupposition. The intended operating system is Linux with a (fairly) recent kernel.

回答1:

This isn't portable, but on many Linux systems, you can write to

/proc/$PID/fd/0

I think this may be one of a very limited number of potentially complicated options if you don't have any other control over the remote process.



回答2:

In most platforms (i.e., operating systems), an existing process's existing file descriptors are inviolate -- the operating system, striving to guarantee process integrity, will be designed to not allow a separate, unrelated process to alter those file descriptors.

Nevertheless, if you do specify a very specific and well-identified platform (ideally including the exact version and release of the operating system in question, since security does tend to get tightened in successive releases compared with preceding ones), it's quite possible that there will be available tricks for your purposes. For example, you may be able to exploit some of the hooks which the operating system intends to be used for "remote debuggers" attaching themselves to existing processes -- if, that is, your very specific OS does offer such hooks (not all do!).

But, if you want a cross-platform solution, no way.

So, I recommend you edit your question, and in particular replace one of the tags with the name of the "one and only" OS you really need to support (in the Q's edited text, please be as specific as possible about the exact versions and releases you absolutely do need to support -- Python has very little indeed to do with the issue, as you need to operate at specific-OS levels, so there's no real need to similarly pinpoint the Python version).