Summary Files Commits Branches @commit @diff @stats
path: root / Year 3 / System programming / Practicum6 / ex4.c
blob: fe0718e16f9aab90b5b0fa2d8f087e7bf155a6cf (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
#include <unistd.h>
#include <stdio.h>
#include <string.h>
#include <sys/types.h>
#include <sys/wait.h>

int main(int argc, char* argv[]) {
	int fileDes[2];
	if (pipe(fileDes) < 0) {
		perror("pipe");
		return 1;
	}

	int f = fork();
	if (f == 0) { // child
		if (close(fileDes[1]) < 0) {
			perror("close");
			return 2;
		}

		char buf[1024];
		int count = argc - 1;
		while (count > 0) {
			read(fileDes[0], &buf, 1024);
			if (buf[0] != '\0') {
				printf("%s", buf);
				count--;
			}
		}
	}
	else {
		if (close(fileDes[0]) < 0) {
			perror("close");
			return 3;
		}

		for (size_t i = 1; i < argc; i++) {
			write(fileDes[1], argv[i], strlen(argv[i]));
			sleep(1);
		}
		int status;
		wait(&status);
	}
	return 0;
}