How to create a new process with command line arguments and pass the PID to the parent process?

I am trying to create a cross-platform function to create a new process using both Unix and Windows.

Using fork () and exec () on Unix is ​​quite simple. Although it’s hard for me to understand Windows. I am sure that you know that exec functions do not return a child pid. On Unix fork, this will do. But on Windows there is no plug. So I tried using WinAPI CreateProcess, but did not find an easy way to add command line arguments.

So, I got a little lost here, if someone knows a way to create a new process with command line arguments and return the child pid to the parent, I would be very grateful if you share your knowledge with me.

+4
source share
1 answer

You can use the createprocess () function in windows.

His signature is below

BOOL WINAPI CreateProcess( _In_opt_ LPCTSTR lpApplicationName, _Inout_opt_ LPTSTR lpCommandLine, _In_opt_ LPSECURITY_ATTRIBUTES lpProcessAttributes, _In_opt_ LPSECURITY_ATTRIBUTES lpThreadAttributes, _In_ BOOL bInheritHandles, _In_ DWORD dwCreationFlags, _In_opt_ LPVOID lpEnvironment, _In_opt_ LPCTSTR lpCurrentDirectory, _In_ LPSTARTUPINFO lpStartupInfo, _Out_ LPPROCESS_INFORMATION lpProcessInformation ); 

Example:

 STARTUPINFO si; PROCESS_INFORMATION pi; //This structure has process id ZeroMemory( &si, sizeof(si) ); si.cb = sizeof(si); ZeroMemory( &pi, sizeof(pi) ); if( argc != 2 ) { printf("Usage: %s [cmdline]\n", argv[0]); return; } // Start the child process. if( !CreateProcess( NULL, // No module name (use command line) argv[1], // Command line NULL, // Process handle not inheritable NULL, // Thread handle not inheritable FALSE, // Set handle inheritance to FALSE 0, // No creation flags NULL, // Use parent environment block NULL, // Use parent starting directory &si, // Pointer to STARTUPINFO structure &pi ) // Pointer to PROCESS_INFORMATION structure ) { printf( "CreateProcess failed (%d).\n", GetLastError() ); return; } // Wait until child process exits. WaitForSingleObject( pi.hProcess, INFINITE ); // Close process and thread handles. CloseHandle( pi.hProcess ); CloseHandle( pi.hThread ); 

http://msdn.microsoft.com/en-us/library/windows/desktop/ms682512(v=vs.85).aspx

+3
source

Source: https://habr.com/ru/post/1486422/


All Articles