Summary Files Commits Branches @commit @diff @stats
path: root / Year 3 / System programming / Practice05 / ex2.c
blob: 85ce0dd5dbab4a3ab94189b7d2fbbe5cc9498b7c (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
#include <unistd.h> // fork, write, close, sleep
#include <fcntl.h> // open
#include <stdio.h> // perror

int main(int argc, char* argv[]) {
	int file = open("test.txt", O_WRONLY);
	if (file < 0) {
		perror("open");
		return 1;
	}
	pid_t f = fork();

	if (f == 0) { // in child
		char buf = 'c';
		for (int i = 0; i < 5; i++) {
			sleep(2);
			if(write(file, &buf, 1) < 0) {
				perror("write");
				return 2;
			}
		}
	}
	else {
		char buf = 'p';
		for (int i = 0; i < 5; i++) {
			if(write(file, &buf, 1) < 0) {
				perror("write");
				return 3;
			}
			sleep(1);
		}
	}
	close(file);
}