forked from MeiK2333/apue
-
Notifications
You must be signed in to change notification settings - Fork 0
/
14.3.2.c
64 lines (54 loc) · 1.35 KB
/
14.3.2.c
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
#include <errno.h>
#include <fcntl.h>
#include <sys/wait.h>
#include "apue.h"
int main(int argc, char* argv[]) {
int fd;
pid_t pid;
char buf[5];
struct stat statbuf;
if (argc != 2) {
fprintf(stderr, "usage: %s filename\n", argv[0]);
exit(1);
}
if ((fd = open(argv[1], O_RDWR | O_CREAT | O_TRUNC, FILE_MODE)) < 0) {
err_sys("open error");
}
if (write(fd, "abcdef", 6) != 6) {
err_sys("write error");
}
if (fstat(fd, &statbuf) < 0) {
err_sys("fstat error");
}
if (fchmod(fd, (statbuf.st_mode & ~S_IXGRP) | S_ISGID) < 0) {
err_sys("fchmod error");
}
TELL_WAIT();
if ((pid = fork()) < 0) {
err_sys("fork error");
} else if (pid > 0) {
if (write_lock(fd, 0, SEEK_SET, 0) < 0) {
err_sys("write_lock error");
}
TELL_CHILD(pid);
if (waitpid(pid, NULL, 0) < 0) {
err_sys("write_lock error");
}
} else {
WAIT_PARENT();
set_fl(fd, O_NONBLOCK);
if (read_lock(fd, 0, SEEK_SET, 0) != -1) {
err_sys("child: read_lock succeeded");
}
printf("read_lock of already-locked region erturns %d\n", errno);
if (lseek(fd, 0, SEEK_SET) == -1) {
err_sys("lseek error");
}
if (read(fd, buf, 2) < 0) {
err_ret("read failed (mandatory locking works)");
} else {
printf("read OK (no mandatory locking), buf = %2.2s\n", buf);
}
}
exit(0);
}