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

USEFUL?
We benefit hugely from resources on the web so we decided we should try and give back some of our knowledge and resources to the community by opening up many of our company’s internal notes and libraries through mini sites like this. We hope you find the site helpful.
Please feel free to comment if you can add help to this page or point out issues and solutions you have found, but please note that we do not provide support on this site. If you need help with a problem please use one of the many online forums.

Comments

  1. Francis Yu

    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.

Comments

Your email address will not be published. Required fields are marked *