Summary Files Commits Branches @commit @diff @stats
path: root / Year 3 / System programming / Practice05 / ex5.c
blob: 8e7bf1523333414d1d2a7e2b7afec791a6389665 (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
#include <unistd.h> // fork, write, read, close, sleep
#include <fcntl.h> // open
#include <stdio.h> // perror
#include <sys/wait.h> // waitpid, WNOHANG

int main(int argc, char* argv[]) {
	int f1 = open(argv[1], O_RDONLY);
	if (f1 < 0) {
		perror("open");
		return 1;
	}

	int f2 = open(argv[2], O_WRONLY | O_CREAT | O_APPEND);
	if (f2 < 0) {
		perror("open");
		return 2;
	}

	pid_t fpid = fork();
	if (fpid == 0) { // in child
		char buf;
		while (read(f1, &buf, 1)) {
			write(f2, &buf, 1);
			sleep(1);
		}
	}
	else {
		int status = -2;
		char buf = 'p';
		while(status == -2) {
			sleep(2);
			write(f2, &buf, 1);
			waitpid(fpid, &status, WNOHANG);
		}
	}

	close(f1);
	close(f2);
}