Summary Files Commits Branches @commit @diff @stats
path: root / Year 3 / System programming / Practicum5 / ex1.c
blob: 85e86bb2ebac06739a6cf2ce7bb8ecd119e35204 (plain) (blame)
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
#include <sys/types.h>
#include <fcntl.h>
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>

int main() {
	pid_t fpid = fork();

	if (fpid < 0) {
		perror("fork");
		return 1;
	}

	int f = open("test.txt", O_CREAT | O_WRONLY | O_APPEND, 0755);
	if (f < 0) {
		perror("open test.txt");
		return 2;
	}

	if (fpid == 0) { // in child
		sleep(2);
		int ws = write(f, "From Child 1\n", 13);

		if (ws < 0) {
			perror("write from child");
			return 3;
		}

		sleep(5);
		ws = write(f, "From Child 2\n", 13);

		if (ws < 0) {
			perror("write from child");
			return 3;
		}
	}
	else {
		int ws = write(f, "From Parent 1\n", 14);

		if (ws < 0) {
			perror("write from child");
			return 3;
		}

		sleep(3);
		ws = write(f, "From Parent 2\n", 14);

		if (ws < 0) {
			perror("write from child");
			return 3;
		}
		sleep(5);
	}
}