File: lock.c

package info (click to toggle)
troffcvt 1.04%2Brepack1-1
  • links: PTS, VCS
  • area: main
  • in suites: bookworm
  • size: 3,416 kB
  • sloc: ansic: 13,110; makefile: 6,847; perl: 1,583; cpp: 333; sh: 215
file content (108 lines) | stat: -rw-r--r-- 1,582 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
/*
 * File-locking calls
 *
 * AcquireLock() - acquire an exclusive lock on an open file
 * ReleaseLock() - release a lock on an open file
 *
 * The argument to both calls is a FILE *
 */

#if !HAS_FCNTL && !HAS_FLOCK
*** error -- neither fcntl() nor flock() are present?
#endif

#include	<stdio.h>
#if HAS_FCNTL
#include	<fcntl.h>
#endif
#if HAS_FLOCK
#include	<sys/file.h>
#endif

#include	"portlib.h"

/*
 * Some braindamaged systems don't define this in fcntl.h.
 */

#ifndef SEEK_SET
#define SEEK_SET 0
#endif


#if HAS_FCNTL		/* fcntl() version of locking functions */
int
AcquireLock (f)
FILE	*f;
{
struct flock	lock;
int	fd;

#ifdef DEBUG
printf ("using fcntl() on fileno %d\n", fileno (f));
#endif
	lock.l_type = F_WRLCK;
	lock.l_start = 0;
	lock.l_whence = SEEK_SET;
	lock.l_len = 0;
	fd = fileno (f);
	if (fcntl (fd, F_SETLK, &lock) == 0)
		return (1);
#ifdef DEBUG
	perror ("AcquireLock");
#endif
	return (0);
}


void
ReleaseLock (f)
FILE	*f;
{
struct flock	lock;
int	fd;

	lock.l_type = F_UNLCK;
	lock.l_start = 0;
	lock.l_whence = SEEK_SET;
	lock.l_len = 0;
	fd = fileno (f);
	(void) fcntl (fd, F_SETLK, &lock);
}

#else

#if HAS_FLOCK		/* flock() version of locking functions */

int
AcquireLock (f)
FILE	*f;
{
int	fd;

#ifdef DEBUG
printf ("using flock() on fileno %d\n", fileno (f));
#endif
	fd = fileno (f);
	if (flock (fd, LOCK_EX | LOCK_NB) == 0)
		return (1);
#ifdef DEBUG
	perror ("AcquireLock");
#endif
	return (0);
}


void
ReleaseLock (f)
FILE	*f;
{
int	fd;

	fd = fileno (f);
	(void) flock (fd, LOCK_UN);
}

#endif /* HAS_FLOCK */

#endif /* HAS_FCNTL */