File: locktest.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 (104 lines) | stat: -rw-r--r-- 2,298 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
/*
 * locktest - test portlib file-locking functions
 *
 * This program tries to acquire a lock.  If the lock is obtained
 * successfully, the program sleeps for 10 seconds, then releases
 * the lock.  To use the program, start one instance, then start
 * another before the first releases the lock.  The first instance
 * should get the lock, the second instance should fail.  When the
 * first instance exits, start a third instance.  The first instance
 * should successfully acquire a lock.
 *
 * Options:
 * -s n		sleep for n seconds instead of default 10
 * -f name	create file with given name instead of default "lock.test"
 *
 * 29 November 1996
 * Paul DuBois
 * dubois@primate.wisc.edu
 * http://www.primate.wisc.edu/people/dubois/
 */

#include	<stdio.h>

#include	"portlib.h"


#ifndef bufSiz
#define bufSiz 1024
#endif

static char	lockFile[bufSiz] = "lock.test";
static int	sleepTime = 10;
static char	*usage = "Usage: locktest [ -s sleeptime ] [ -f lockfile ]";

int
main (argc, argv)
int	argc;
char	*argv[];
{
FILE	*f;

	--argc;			/* skip program name */
	++argv;
	while (argc > 0 && argv[0][0] == '-')
	{
		if (strcmp (argv[0], "-s") == 0)
		{
			if (argc < 2)
			{
				fprintf (stderr, "%s\n", usage);
				exit (1);
			}
			sleepTime = StrToInt (argv[1]);
			argc -= 2;
			argv += 2;
		}
		else if (strcmp (argv[0], "-f") == 0)
		{
			if (argc < 2)
			{
				fprintf (stderr, "%s\n", usage);
				exit (1);
			}
			(void) strcpy (lockFile, argv[1]);
			argc -= 2;
			argv += 2;
		}
		else
		{
			fprintf (stderr, "unknown option: %s\n", argv[0]);
			fprintf (stderr, "%s\n", usage);
			exit (1);
		}
	}
	if (argc != 0)
	{
		fprintf (stderr, "%s\n", usage);
		exit (1);
	}
	printf ("opening \"%s\" file\n", lockFile);
	/*
	 * Create file if it doesn't exist, but if it does exist,
	 * don't overwrite the contents.  We just want to lock it,
	 * not destroy it.
	 */
	if ((f = fopen (lockFile, "a+")) == (FILE *) NULL)
	{
		printf ("could not open \"%s\", exiting\n", lockFile);
		exit (1);
	}
	printf ("trying to acquire lock\n");
	if (AcquireLock (f) == 0)
	{
		printf ("lock not acquired, exiting\n");
		(void) fclose (f);
		exit (1);
	}
	printf ("lock acquired successfully\n");
	sleep (sleepTime);
	printf ("releasing lock\n");
	ReleaseLock (f);
	(void) fclose (f);
	exit (0);
}