Redirect IO of process to Windows socket

被刻印的时光 ゝ 提交于 2019-12-05 16:14:48

Windows treats almost everything as a HANDLE. Sockets, which aren't kernel objects, are an exception, and they can't be used for redirection. You'll need to use a pipe, and if you need to send data to/from a socket, you'll need a helper process to copy data between the pipe and socket.

Have a look at netcat source code for the win32 version (if you can find it), it does pretty much exactly socket <-> stdin and stdout forwarding.

Actually, you can redirect IO to sockets. Just make sure you open the socket with WSASocket instead of socket(), and do NOT specify the WSA_FLAG_OVERLAPPED.

The reason for this is a bit involved. Any "Standard Handles" that you supply to CreateProcess for I/O redirection must be non-overlapped (i.e, do not support overlapped I/O). sockets on Windows are opened overlapped when created with socket() and non-overlapped if created as above with WSASocket.

Also make sure you set bInheritHandles to TRUE in the StartupInfo

Sockets cannot be used directly for redirection. When launching the external process, use CreatePipe() to create anonymous pipes for the redirected STDIN/OUT/ERR handles of the process, then use ReadFile() and WriteFile() (or equivilents) with send() and recv() to manually proxy the data between the socket and the process yourself via the pipes. In other words, when data arrives to the socket, read the data from the socket and write it to the STDIN pipe. When the process outputs data, read from the STDOUT/ERR pipes and write it to the socket.

It's not correct to say that socket handles cannot be used for redirected IO to child processes. We do it all the time for CGI in our web server code. We don't use named or unnamed pipes, or intermediary processes.

a_mole is correct. You just need non-overlapped sockets.

You can either use WSASocket, or if you created the socket already with socket (or can't use WSASocket on your target OS, e.g. Pre Windows 7 SP1) you can use setsockopt to set the current thread's SO_OPENTYPE to SO_SYNCHRONOUS_NONALERT

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!