Tech Support Guy banner
Not open for further replies.
1 - 2 of 2 Posts

2 Posts
Discussion Starter · #1 ·
Hey guys...
Could anyone help me with this concern:(

Here is the concern

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 lock_passwd()
int rv = 0; /* default return value */
if ( link(“/etc/passwd”, “ / etc/passwd. LCK = = - 1 )
rv = ( errno = = EEXISTS ? 1 : 2 ) ;
return rv;
(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?

I would highly appreciate any help
I am new to Unix...
Thanks in Advance

431 Posts
There are a lot of questions embedded in your post!

1. link() simply creates a new directory entry for a file. There is still only one file,
but link() creates a new name for that file.

2. unlink() deletes a directory entry and is what you'll use in unlock_passwd(). The file is not erased, but its directory entry is gone.

3. link() sets errno to EEXISTS when it attempts to create a directory entry where one already exists by the same name.

4. The whole idea of using this approach is to make the file modification atomic. Atomicity refers to the concept of grouping one or more tasks together so that each of them must succeed or none of them succeeds.

5. I would look at the stat() function in answering item d.

6. The problem is unlikely to occur in changing of passwords, because the likelihood of two users changing their passwords at EXACTLY the same time is very low. However, I've had the same file opened in vi in two different windows and saved the file in the "wrong" order before. I hate it when that happens.

Hope this helps...
1 - 2 of 2 Posts
Not open for further replies.