Call On A Background Thread
fork creates a clone of the current process on a new thread. Use with execlp to trigger other processes, e.g. open another application
int pid;
pid = fork();
if (pid == 0)
{
//Child thread
printf("I am the child\n");
//Do something
execlp("/usr/bin/omxplayer", " ", "/home/pi/projects/game/audio/alpha.wav", NULL); //Execute file: file, arguments (1 or more strings followed by NULL - omxplayer has [OPTIONS] [FILE] hence the blank string)
//Exit fork
_exit(0); //Don't forget to exit!
}
else
{
//Parent thread
printf("I am the parent\n");
wait(); //Optional if you want to wait on the child thread, remove if not
}
Do something that might take a while without waiting example
pid = fork();
if (pid == 0)
{
//This is the child thread
system("sudo ifdown wlan1; sudo ifup wlan1 &"); //'&' means do in background
_exit(0);
}
IMPORTANT NOTE:
The child process once it dies remains in the Linux process table marked as <defunct>. You’ll get one added every time you use this fork technique. They remain so the OS can give the parent process a handle to the child exit status and will only be removed when the main process dies. Whilst sometimes considered annoying they consume no resources and are not typically an issue unless there are a lots of them
9 years ago
Hi, when I was experimenting with this function, by including these lines into my main( ), I got some warning statements like “implicit declaration of function ‘fork’…… I guess I must be missing a line upfront like #include. Could you please point me to the direction where I can find all these declarations. Thank you very much.
Francis, a newbe to the Raspberry Pi world.