Exam 2, Question 4 Solution

Written by Sanghwan Lee

Question 4. Atomic Operations. (20 pts.)

Do the following operations need to be atomic? For each, explain why or why not.

A. open with the O_CREAT flag set.

YES

The open system call with the O_CREAT first checks whether the file exists and if the file doesn't exist, it creates the file.
Let's assume that the file doesn't exist and Process 1 and Process 2 attempt to open a file with the O_CREAT flag set simultaneously.

If the two operations, check and create are not atomic, then the following sequence of events could happen.

By the above sequence, there will be 2 files with the same name, which is not allowed in POSIX.

Another problem is about the inconsistent information.
To create a file, open has to reserve a new i-node and sets i-node information(such as mode, time, etc) of the file in the i-node.
And put the file name to a derectory block.
If the open is interrupted by other process before completing all of this procedure,
then some information inconsistency will be shown to other processes.
For example, there can be an i-node for the file, but there's no information in the directory block.
That makes the file system unstable.

So open with the O_CREAT flag should occur in an atomic fashion.




B. open without the O_CREAT flag set.

NO


Since there's no O_CREAT flag, if the file doesn't exist, then open will return with appropriate return value.
If the file exists, open will open the file.
Multiple processes can open a file simultaneously, so
open without the O_CREAT flag set doesn't have to be atomic.




C. fcntl with the F_SETLK command.

YES

fcntl with the F_SETLK do the two things. First one is to check if the file has locks, and the second one is to set a lock on the file.
If it is not atomic operation, then when two processes attempt to set a lock on a same file, it can be an erroneous behavior.
Consider the following situation.

By the above sequence, the locking of the file by process 1 will be annihilated by the locking by process 2.
So fcntl with the F_SETLK command should occur in an atomic fashion.




D. fcntl with the F_SETLKW command.

YES


One disastrous situation is same as that of part C.

The other one is about the queuing.
fcntl with the F_SETLKW command should put the process ID onto a queue if there's already a locking on the file.
But consider the following sequences.
Let's assume the process 1 has the locking on the file.

And the process 2 should wait forever since the process 1 already released the locking
so that the process 2 cannot get the signal from process 1.
So fcntl with the F_ SETLKW command should occur in an atomic fashion.