Windows
You always have to create a totally new process via a CreateProcess(…) call.
#include <iostream> int main() { std::cout << "I'm a child" << std::endl; return 0; }
#include <windows.h> #include <iostream> int main() { char path[] = ".\\child.exe"; char args[] = "child.exe"; STARTUPINFO startupInfo = { sizeof(startupInfo) }; PROCESS_INFORMATION processInfo; if (!CreateProcess(path, args, NULL, NULL, TRUE, 0, NULL, NULL, &startupInfo, &processInfo)) { /* Couldn't create process */ std::cout << "Couldn't create process" << std::endl; } std::cout << "I'm the parent" << std::endl; WaitForSingleObject(processInfo.hProcess, INFINITE); return 0; }
Linux
You can either just copy the process (1) or copy it and replace the program (2).
(1) Just copy parent process
#include <sys/types.h> #include <unistd.h> #include <iostream> int main() { pid_t pid = fork(); if (pid == -1) { /* Couldn't fork */ std::cout << "Couldn't fork" << std::endl; } else if (pid == 0) { /* Child process */ std::cout << "I'm the child" << std::endl; } else { /* Parent process */ std::cout << "I'm the parent" << std::endl; } return 0; }
(2) Copy parent process and replace program
#include <sys/types.h> #include <sys/wait.h> #include <unistd.h> #include <iostream> int main() { pid_t pid = fork(); if (pid == -1) { /* Couldn't fork */ std::cout << "Couldn't fork" << std::endl; } else if (pid == 0) { /* Child process */ execlp("./child.out", "child.out", NULL); } else { /* Parent process */ std::cout << "I'm the parent" << std::endl; waitpid(pid, NULL, 0); } return 0; }
In the past fork() would do straight away a copy of the memory of the parent process. That makes no sence at all if you call exec(…) afterwards. These days it only starts to copy that memory as soon as it gets modified.