My project has two programs: Parent and Child.
In Parent: has one socket waiting connection from client. When Parent accepts connection, it generates Child process and passes socket to Child.
SOCKET newSock = accept(listenSock, 0, 0);
char cmd[1024];
sprintf(cmd, "%s %d", "Child.exe", newSock);
result = CreateProcess( NULL, cmd, NULL, NULL, TRUE, CREATE_NEW_CONSOLE, NULL, NULL, &startupInfo, &processInformation);
Client and Child process transfer data successfully.
But when I searches Google and some people wrote that : must call function WSADuplicateSocket(), after that pass socket to child process.
Pleas help me show the different between the two ways? If I don't call WSADuplicateSocket() whether my program has any error or not?
Setting Parameter bInheritHandles in CreateProcess to TRUE you allow a child process to get all inheritable handle. Socket handles are inheritable always. So you don't need any extra call.
WSADuplicateSocket is required only if you handle was not inherited (socket was created after child process start or bInheritHandles is FALSE in CreateProcess)
Well, for starters, a SOCKET on Windows is a handle (ie a pointer) and thus is subject to 32/64-bit byte sizes, so %d is not adequate if your app runs on a 64-bit system. You would have to use %p instead.
Aside from that, WSADuplicateSocket() is the correct approach. MSDN says as much:
Shared Sockets
The WSADuplicateSocket function is introduced to enable socket sharing across processes.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With