-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathreader_writer_process.c
66 lines (48 loc) · 1.11 KB
/
reader_writer_process.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
65
66
#include <stdio.h>
#include <fcntl.h>
#include <unistd.h>
#include <stdlib.h>
#define BUF_SIZE 512
void process_A() {
int fd;
char buf[BUF_SIZE];
fd = open("testfile.txt", O_RDONLY);
if (fd < 0) {
perror("Error opening file in A");
exit(1);
}
read(fd, buf, sizeof(buf));
printf("Process A First read: %s\n", buf);
read(fd, buf, sizeof(buf));
printf("Process A Second read: %s\n", buf);
close(fd);
}
void process_B() {
int fd;
char buf[BUF_SIZE];
for (int i = 0; i < sizeof(buf); i++) {
buf[i] = 'a';
}
fd = open("testfile.txt", O_WRONLY | O_CREAT, 0644);
if (fd < 0) {
perror("Error opening file in B");
exit(1);
}
write(fd, buf, sizeof(buf));
printf("Process B First write done\n");
write(fd, buf, sizeof(buf));
printf("Process B Second write done\n");
close(fd);
}
int main() {
int pid = fork();
if (pid == 0) {
process_A();
} else if (pid > 0) {
process_B();
} else {
perror("Fork failed");
exit(1);
}
return 0;
}