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

From: Steffen (s.weinstock_at_gmx.de)
Date: 08/31/05


Date: Wed, 31 Aug 2005 15:13:16 +0200

Hi,

doomster@gmail.com wrote:
> 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
> 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)
>
>
> 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.

Can you provide a minimal version of program 1? Just to see what you are
actually doing. Do you really need record locking? If file locking does
the job you can use lockf/flock, which are simpler to handle.

> 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.

Well, you said all fcntl-calls of program 2 returned -1. Therefore I
wouldn't give anything on what you got back in the lock-structure.

Steffen



Relevant Pages