From 92478827872214a442c96891a607d0781cfa6dd8 Mon Sep 17 00:00:00 2001 From: Syndamia Date: Sat, 20 Jan 2024 14:54:25 +0200 Subject: [SP/P09] Solved exercises --- Year 3/System programming/Practice09/ex4.c | 48 ++++++++++++++++++++++++++++++ 1 file changed, 48 insertions(+) create mode 100644 Year 3/System programming/Practice09/ex4.c (limited to 'Year 3/System programming/Practice09/ex4.c') diff --git a/Year 3/System programming/Practice09/ex4.c b/Year 3/System programming/Practice09/ex4.c new file mode 100644 index 0000000..3e6f871 --- /dev/null +++ b/Year 3/System programming/Practice09/ex4.c @@ -0,0 +1,48 @@ +#include +#include +#include +#include +#include +#include +#include + +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 amount; + while ((amount = read(0, buf, 128))) { + if (amount < 128) buf[amount] = '\0'; + mq_send(mq, buf, 128, 0); + } + } + else { + int fd = open(argv[1], O_WRONLY | O_TRUNC | O_CREAT, 0755); + + while (!waitpid(fp, NULL, WNOHANG)) { + mq_receive(mq, buf, 128, NULL); + write(fd, buf, strlen(buf)); + } + + mq_getattr(mq, &mqattrs); + while (mqattrs.mq_curmsgs-- > 0) { + mq_receive(mq, buf, 128, NULL); + write(fd, buf, strlen(buf)); + } + + close(fd); + } + + mq_close(mq); + if (fp != 0) + mq_unlink("/spqueue"); + + return 0; +} -- cgit v1.3.1-26-gb76a