Using windows sockets for a new process I/O

615 views Asked by At

Are there any restrictions to the types of I/O kernel objects that one can use for redirection when calling CreateProcess()?

As can be seen in the documentation, one of the parameters the function receives is the STARTUPINFO structure. Within this structure, one can specify handles for both input, output and errors. However, it's not mentioned what specific kinds of I/O kernel objects can be use.

I have tested the use of windows sockets as I/O devices, and found that it works. However, I assume that the nature of such a device is rather different than a file object, which makes me wonder if it was actually intended that sockets can be used for this purpose.

3

There are 3 answers

0
Claudi On

Well, not sure if I'm answering your question, but in terms of inheritance, as of MSDN documentation states, one can modify the inheritance policy of a socket by means of SetHandleInformation(). This way you can prevent child processes from inherit a listening socket of the parent process.

0
Harry Johnston On

I don't believe this is documented.

However, common practice says that the standard I/O handles may be any such stream devices as TCP/IP sockets, COM or LPT ports, files, pipes, and so on. I believe there is sample code on MSDN for several of these scenarios.

(The default standard I/O handles are to the console, not to a file, so we can safely assume at least that they do not have to be file handles!)

2
Remy Lebeau On

When using STARTF_USESTDHANDLES to specify STDIN/OUT/ERR handles for CreateProcess(), they are supposed to be valid kernel objects that are compatible with CloseHandle() (since that is stated as much in the STARTUPINFO documentation). Sockets are not kernel objects and do not meet the CloseHandle() requirement (although sockets can be used with the ReadFile() and WriteFile() kernel functions).

When a caller is launching a redirected process on behalf of a socket connection, the typical scenario is for the caller to use an anonymous pipe via CreatePipe() for the redirection and then proxy data between the socket connection and the pipe as needed.

That being said, one of the answers to another question states that is possible to use a socket for redirection, but only if the socket was created using WSASocket() with the WSA_FLAG_OVERLAPPED flag omitted, since redirection does not allow overlapped handles to be used. I have not personally attempted that solution myself, so I do not know I it works or not. It is better to be safe and use a pipe instead, especially if you have no control over (or knowledge of) how the socket was created.