interrupt a blocking lock(F_SETLKW)

Hi all,

I use F_SETLKW to lock a file or keep waiting. How can I interrupt the blocking lock after waiting for a period? I want to add an argument to let user set waiting time. Maybe I can use non-blocking lock(F_SETLK) and a loop to check it. But it may consume too many resources. Any idea?:confused:

p.s: C/C++, LINUX platform

Thanks,
Marco Chen

alarm/SIGALRM sounds like the right thing here.

That what I'm trying now. But it's weird. I wrote a signal handler function to judge if set lock successfully or wait timeout. There are A, B ,C three processes trying to get file lock. A starts to lock file first, then B starts waiting, then C starts waitng. (alarm after ten seconds). Now A releases its lock but C gets file lock instead of B. I don't know how could it happen. Since I use "F_SETLKW", it sholud wait sequentially.

//timeout handler function
static void timeout_handler (int signum) {
struct flock fl = { F_WRLCK, SEEK_SET, 0, 0, 0 };
int fd;
fl.l_type = F_RDLCK;

printf\("enter locking timeout check\\n"\);

if \(\(fd = open\("lock.c", O_RDWR\)\) == -1\) \{
    perror\("open"\);
    exit\(1\);
\}

if \(fcntl\(fd, F_SETLK, &fl\) == -1\)\{
  printf\("timeout pid: %d\\n",fl.l_pid\);
  printf\("Timeout!\\n"\);
  exit\(1\);
\}

}

//main function as below
......

printf\("Press <RETURN> to try to get lock: "\);
getchar\(\);
printf\("Trying to get lock..."\);

struct sigaction action, old_action;
unsigned int old_timeout;

/* Cancel any existing alarm.  */
old_timeout = alarm \(0\);

/* Establish signal handler.  */
action.sa_handler = timeout_handler;
sigemptyset \(&action.sa_mask\);
action.sa_flags = SA_RESTART;
sigaction \(SIGALRM, &action, &old_action\);

alarm\(TIMEOUT\);

fcntl\(fd, F_SETLKW, &fl\);

/* Reset the signal handler and alarm.  */
sigaction \(SIGALRM, &old_action, NULL\);
alarm\(old_timeout\);

........

A, B and C are all independent processes. There is no rule that says that he who starts waiting for a lock first is the first to get it, but there is a rule that says only one can have the lock at any time.

It may not seem fair, but it is democratic. :slight_smile:

thank you, porter.