Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

pass socket to child process

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?


2 Answers

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)

like image 82
sliser Avatar answered Jun 03 '26 00:06

sliser


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.

like image 34
Remy Lebeau Avatar answered Jun 02 '26 23:06

Remy Lebeau



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!