Process Synchronization in Linux

Process Synchronization is the principle of time slicing where each process is give a little bit of time for its execution. So we see the two fundamental concepts in Linux is processes and time slice. The way we create a new process in Linux is using the

fork() command

Fork creates a child process that is a duplicate of the parent process. Every process in Linux has an PID (process id) which will help us diffentiate between one another.

Ok so we have a child that is a duplicate of a parent. Let’s say the parent terminates before the child process. We will have a fatherless child which is called a orphaned process

Example

#include
main()
{
int pid;
pid=fork();

if (pid!=0)
{
     printf("This is a parent process");
     sleep(20);
}
}

Output

This is the parent process

Only one output is shown as the parent is executed which mean the child never executes an becomes orphaned. When you run ps -el you can see the parent process running and exiting after 20 sec.

There are various statuses for a process

  • Running (R)
  • Orphaned (O)
  • Sleeping (S)
  • Zombie (Z)

When we introduce the wait() command into our program it will help us synchronize the processes. Example below:

#include
main()
{
int i = 0;
int pid;
pid = fork();
if (pid == 0)
{
	printf("Child process starts \n");
	for(i=0;i<100;i++)
	printf("%d\t", i);
	printf("Child process ends");
}
else 
{
     wait(0);
     for (i=0;i<100;i++)
	printf("%d\t", i);
printf("Parent process ends \n");

}
}

Linux is smart enough to recognize a deadlock situation and sort it out. When Linux occurs a deadlock it will print an error message and kill the parent process so you are not stuck with orphaned child processes.

Below is an example on how to implement the lockf() function to lock a process. When two processes want to write to the same file while the first processes already locked the first 10 bytes.

#include
#include
#include
main()
{
	int fd, pid;
	fd = open("lockfile", O_RDWR);
	lockf(fd, F_LOCK, 10);
	printf("Parent locked 10 chars\n");
	pid = fork();
	if (pid == 0)
	{
		lockf(fd, F_LOCK, 10);
		printf("End of first Child process \n");
	}
	else
	{
		wait(0);
		printf("End of parent process \n");
	}

}

Linux provides more primitives know as semaphores. They let multiple processes syncronize their access to shared memory.

1 Comment

  1. liz says:

    thanks a lot this really come handy and timely

Leave a Comment

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s