News

Process synchronisation in Linux

The two fundamental concepts in a Linux operating system are processes and time slice. A process is an instance of a program that is being executed by the computer’s operating system. When we say that two computers are communicating with each other, we mean that two processes, one running on

We can use files to provide resource synchronisation among various processes. If two processes have access to the same file and perform the same set of operations, then it could really mess up the things. When two processes are trying to write into the same file, the data they write will all be jumbled up. The best way is to ensure that only one process is allowed to write into the file at one time. In other words, we need to allow the first process to lock the file, carry out the operations and only when it has finished its work, unlock the file so that the second process can access it.

Let us take a look at an example of two programs to understand this:

[Program 1]
#include<stdio.h>
#include<fcntl.h>
#include<unistd.h>
main()
{
int fd,i;
fd = open(“testfile”,O_APPEND | O_RDWR | O_CREAT, 0666);
lockf(fd,F_LOCK,0);
for(i=0;i<2000;i++)
write(fd,”A”,1);
}

[Program 2]
#include<stdio.h>
#include<fcntl.h>
#include<unistd.h>
main()
{
int fd,i;
fd = open(“testfile”,O_APPEND | O_RDWR | O_CREAT, 0666);
lockf(fd,F_LOCK,0);
for(i=0;i<2000;i++)
write(fd,”B”,1);
}

Man page details of lockf system call
First, make sure that both the above (program 1 and program 2) are run in the background, one after the other. Let us see the flow in the above two programs – time slice is given to the first process. This results in the opening of a file (in append mode). Then lockf statement (Fig 14 above) will get executed. A value of 0 as a third parameter means that the entire file will be locked. In other words, the first process locks the entire file so that the file can be accessed only by it. Now the process proceeds further and executes the last write statement. If the time slice is given to the second program, it will be unable to write into the file as the file is locked (by the first process). So the second process needs to wait till that lock on the file is removed. Once the first process completes its execution, it will get terminated and as a result, the lock will be removed. Now the second process starts its execution, locks the file and then writes data into the file. We can understand here that the data written by the second process will not overwrite the data written by the first process. Please note that in the above situation, an unlock has been performed by default.

×