Jonas Byström
Jonas Byström

Reputation: 26179

How to duplicate current process?

What's the easiest way to duplicate the current process, to spawn another instance in Windows? I know Linux has fork(), but all I need is to run main in the same process again, probably using CreateProcess() with the correct arguments.

Upvotes: 2

Views: 2786

Answers (2)

wallyk
wallyk

Reputation: 57794

Cygwin implements fork() within its managed environment, but even that is an intricate square dance in getting the child to catch up with the parent to accurately replicate POSIX behavior.

It seems like you don't need to emulate fork(), but fork()/exec(). For that, gathering the environment variables, program parameters and passing them to CreateProcess() should be enough. There are options to copy the file descriptors to the child too. See CreateProcess's documentation.

Upvotes: 0

Jonas Byström
Jonas Byström

Reputation: 26179

As @DavidHeffernan commented:

STARTUPINFO si;
::memset(&si, 0, sizeof(si));
si.cb = sizeof(si);
PROCESS_INFORMATION pi;
::CreateProcess(NULL, ::GetCommandLine(), NULL, NULL, FALSE, 0, NULL, NULL, &si, &pi);

Upvotes: 1

Related Questions