UNIX Socket FAQ

A forum for questions and answers about network programming on Linux and all other Unix-like systems

You are not logged in.

  • Index
  • » C
  • » file open in c

#1 2009-12-03 09:59 PM

rishisoft1
Member
Registered: 2009-10-30
Posts: 5

Re: file open in c

Hi,
  I have  taken write lock on one file using fcntl and  writting some data in that. Let say I open the same file using fopen in another program and  start writting in the same file.  How  can I avoid  this?  as I have already taken  write lock on that, however I am able to modify the file after opening the file using fopen  And  writting using fwrite.
Is any way to display  error message "file locked by another program"  when I open the open the file using fopen
.

prog1.c
------
if ((fd = open("size_log", O_RDWR)) == -1)
perror("open");
                exit(1);
        }

if (fcntl(fd, F_SETLKW, &fl) == -1) {
                perror("fcntl");
                exit(1);
        }


prog2.c
-------
FILE *ptr=if(fopen(("size_log", "w"))==NULL
  printf("File locked by prog1.c\n");

Offline

#2 2009-12-04 12:46 AM

i3839
Oddministrator
From: Amsterdam
Registered: 2003-06-07
Posts: 2,239

Re: file open in c

It's an advisory lock, so it only works for other programs also using fcntl()
file locking. This is generally what you want. If you want mandatory locking
on Linux, read: linux/Documentation/filesystems/mandatory-locking.txt

However, the proper thing to do is to try and take the lock with the other
program too, before the fopen, and if that fails print out your message.

Offline

#3 2009-12-04 12:52 AM

RobSeace
Administrator
From: Boston, MA
Registered: 2002-06-12
Posts: 3,839
Website

Re: file open in c

Offline

#4 2010-01-27 11:32 PM

ice9_us
Member
Registered: 2010-01-27
Posts: 4

Re: file open in c

fopen() function checks for locks before doing the lock..
which will hang/block on the fopen call till the lock is released...

Offline

#5 2010-01-28 02:50 PM

RobSeace
Administrator
From: Boston, MA
Registered: 2002-06-12
Posts: 3,839
Website

Re: file open in c

Offline

#6 2010-01-28 04:24 PM

ice9_us
Member
Registered: 2010-01-27
Posts: 4

Re: file open in c

i miss typed that " checks for locks before doing locks()" is not correct..
that is what i typed but not what i wanted to say...
sorry for my fast typing and zero thinking...
proof reading would help...

fopen  is forced by the kernel to block on its call when a lock is set before being allowed to go on..

Offline

#7 2010-01-28 09:39 PM

RobSeace
Administrator
From: Boston, MA
Registered: 2002-06-12
Posts: 3,839
Website

Re: file open in c

Offline

  • Index
  • » C
  • » file open in c

Board footer

Powered by FluxBB