Redirect IO of process to Windows socket

前端 未结 4 533
轻奢々
轻奢々 2021-01-14 02:50

I am new to winsock, I tried to write a server socket that accepts new connection, then it calls an external executable file. How can we redirect the stdin and stdout of the

相关标签:
4条回答
  • 2021-01-14 03:30

    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.

    0 讨论(0)
  • 2021-01-14 03:36

    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

    0 讨论(0)
  • 2021-01-14 03:44

    Overlapped sockets (such as created with socket()) cannot be used directly for I/O redirection.

    When launching the external process, use CreatePipe() instead 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.

    0 讨论(0)
  • 2021-01-14 03:51

    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

    0 讨论(0)
提交回复
热议问题