Fork
I believe this blog post explains in detail about fork
and wait
, but I just want my small example here.
Linux only
Execution sequence is interesting in this case
#include <iostream>
#include <sys/wait.h> // wait
#include <unistd.h> // fork, exec
const char* const long_argv[] = {"./long_process.sh", NULL};
int main(int argc, char const *argv[])
{
if (fork() == 0) {
std::cout << "child process" << std::endl;
execvp(long_argv[0], const_cast<char* const *>(long_argv));
} else {
std::cout << "parent process" << std::endl;
}
int status;
wait(&status);
std::cout << "parent done" << std::endl;
return 0;
}
#!/bin/bash
for i in {1..10}; do
echo $i
sleep 1
done
You should be carefull when call functions like system
or fork
itself in applications that consume a lot of memory (like games) because fork will clone the application process first which wil require free space equal at least to current needs of the application.