Using link() for locking A common race condition involves two processes trying to update the same file at the same time. For example, when you change your password on some system, the passwd program rewrites the file /etc/passwd. What if two users changed their password at the same time?
One technique that prevents simultaneous access to a file is to exploit an important feature
of the link system call. Consider this code:
tries to make a link called /etc/passwd.ICX
' returns 0 if ok, 1 if already locked, 2 if other problem
int rv = 0; /* default return value */
if ( link(/etc/passwd, / etc/passwd. LCK = = - 1 )
rv = ( errno = = EEXISTS ? 1 : 2 ) ;
(a) If two processes execute this code at the same instant, only one will succeed. What is
it about the link system call that makes it a useful way to lock files?
(b) Write a short program that uses this technique to append a line of text to a file.Your program should attempt to make the link. If the link succeeds, the program can open the file, append the line, then delete the link. If the link fails, your program should use sleep(1) to wait a second then try again. Make sure your programdoes not wait forever.
(c) Write the unlock_passwd function that undoes lock_passwd.
(d) The example shown allows processes to lock an existing file, but how can a program
use link to prevent two processes from both creating the same file?
(e) Study the command vipw. Does vipw use links for locks?