Summary Files Commits Branches @commit @diff @stats
path: root / Year 3 / System programming / Practice09 / ex3.c
blob: 71884917c2632be0484d7ad4175e593e9fc80bbe (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
#include <sys/wait.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <mqueue.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>

int main(int argc, char* argv[]) {
	struct mq_attr mqattrs = {
		.mq_maxmsg = 10,
		.mq_msgsize = 128,
	};
	mqd_t mq = mq_open("/spqueue", O_RDWR | O_CREAT, 0700, &mqattrs);

	char buf[128];

	pid_t fp = fork();
	if (fp == 0) { // child
		int file = open(argv[1], O_RDONLY);
		int amount = 0;
		while ((amount = read(file, buf, 128))) {
			if (amount < 128) buf[amount] = '\0';
			mq_send(mq, buf, 128, 0);
		}
		close(file);
	}
	else {
		while (!waitpid(fp, NULL, WNOHANG)) {
			mq_receive(mq, buf, 128, NULL);
			printf("%s", buf);
		}

		mq_getattr(mq, &mqattrs);
		while (mqattrs.mq_curmsgs-- > 0) {
			mq_receive(mq, buf, 128, NULL);
			printf("%s", buf);
		}
	}

	mq_close(mq);
	if (fp != 0)
		mq_unlink("/spqueue");

	return 0;
}