| 1 |
/*********************************************************************** |
| 2 |
* Code listing from "Advanced Linux Programming," by CodeSourcery LLC * |
| 3 |
* Copyright (C) 2001 by New Riders Publishing * |
| 4 |
* See COPYRIGHT for license information. * |
| 5 |
***********************************************************************/ |
| 6 |
|
| 7 |
#include <fcntl.h> |
| 8 |
#include <stdio.h> |
| 9 |
#include <string.h> |
| 10 |
#include <unistd.h> |
| 11 |
|
| 12 |
int main (int argc, char* argv[]) |
| 13 |
{ |
| 14 |
char* file = argv[1]; |
| 15 |
int fd; |
| 16 |
struct flock lock; |
| 17 |
|
| 18 |
printf ("opening %s\n", file); |
| 19 |
/* Open a file descriptor to the file. */ |
| 20 |
fd = open (file, O_WRONLY); |
| 21 |
printf ("locking\n"); |
| 22 |
/* Initialize the flock structure. */ |
| 23 |
memset (&lock, 0, sizeof(lock)); |
| 24 |
lock.l_type = F_WRLCK; |
| 25 |
/* Place a write lock on the file. */ |
| 26 |
fcntl (fd, F_SETLKW, &lock); |
| 27 |
|
| 28 |
printf ("locked; hit enter to unlock... "); |
| 29 |
/* Wait for the user to hit enter. */ |
| 30 |
getchar (); |
| 31 |
|
| 32 |
printf ("unlocking\n"); |
| 33 |
/* Release the lock. */ |
| 34 |
lock.l_type = F_UNLCK; |
| 35 |
fcntl (fd, F_SETLKW, &lock); |
| 36 |
|
| 37 |
close (fd); |
| 38 |
return 0; |
| 39 |
} |