Anybody have any experience with locking/unlocking files using the fcntl() system function?

doomster_at_gmail.com
Date: 08/31/05


Date: 30 Aug 2005 20:02:13 -0700

I'm on a Solaris 10 using gcc to compile a program.

I want to test locking on a certain file.

I'm observing a weird situation.

I wrote two programs that are very similar....

Prog 1:
1) uses open() to open the file in question
2) does a fcntl (F_GETLK)
3) does a fcntl (F_SETLK, F_RDLCK)
4) does a fcntl (F_GETLK)
5) does a fcntl (F_SETLK, F_UNLCK)
6) does a fcntl (F_GETLK)

Prog 2:
1) uses fopen() to open the file in question
// I know I'm supposed to use open() and file descriptors with fcntl()
but this sorta works better than open(); I'll explain more

2) does a fcntl (F_GETLK)
3) does a fcntl (F_SETLK, F_RDLCK)
4) does a fcntl (F_GETLK)
5) does a fcntl (F_SETLK, F_UNLCK)
6) does a fcntl (F_GETLK)

Now, with fcntl(), I know I'm supposed to pass it a file descriptor,
not a file pointer, so I should open the file using open() rather than
fopen(). But here's what happens.

1) In both programs, the first fcntl() [Step 2] call returns an error
status (-1)

2) In Program 2, all fcntl() calls return an error status (-1). I
expect this because I'm using a file pointer rather than a file handle
in the fcntl() call.

3) In Program 1, when I use a file handle, the 3rd fcntl() [Step 4]
returns
a F_UNLCK status in the flock structure.

After the 5th fcntl() call [Step 6], I get the same F_UNLCK status.

4) In Program 2, when I use a file pointer, the 3rd fcntl() [Step 4]
returns a F_RDLCK status.

In Program 2, after the 5th fcntl() call [Step 6], I get a F_UNLCK
status

How come fcntl() doesn't seem to work at setting locks when I use a
file handle but works when I use a file pointer even though all calls
to fcntl() using a file pointer return an error status?

fcntl() doesn't like that I use file pointers but does the actual
locking/unlocking of files.

But when I use the recommended file handles, fcntl() does no locking...

Anybody have more expertise about this than I do?

Doomster
doomster -at- gmail -dot- com



Relevant Pages