-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathflock-fork.c
More file actions
54 lines (47 loc) · 919 Bytes
/
Copy pathflock-fork.c
File metadata and controls
54 lines (47 loc) · 919 Bytes
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
#include <string.h>
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/file.h>
void
usage(const char* name, FILE *fp, int status)
{
fprintf(fp, "Usage: %s filname\n", name);
exit(status);
}
int
main(int argc, char **argv)
{
if (argc != 2)
{
fprintf(stderr, "Unexpected number of arguments\n");
return 1;
}
if (strcmp(argv[1], "-h") == 0 || strcmp(argv[1], "--help") == 0)
usage(argv[0], stdout, 0);
int fd = open(argv[1], O_RDWR);
if (fd < 0)
{
perror("open");
return 1;
}
if (flock(fd, LOCK_EX) < 0)
{
perror("flock");
return 1;
}
fprintf(stderr, "A lock is held. press [enter] for forking: ");
getchar();
pid_t pid = fork();
if (pid < 0)
{
perror("fork");
return 1;
}
if (pid == 0)
sleep(300); /* child */
else
exit(0); /* parent */
return 0;
}