Summary Files Commits Branches @commit @diff @stats
path: root / Year 3 / System programming / Practice09 / ex3.c
diff options
context:
space:
mode:
Commit92478827872214a442c96891a607d0781cfa6dd8 (patch)
Author
 Syndamia <kamen@syndamia.com>
2024-01-20 14:54:25 +0200
Committer
 Syndamia <kamen@syndamia.com>
2024-01-20 14:54:25 +0200
Files2bdbb6d4511eb3ad82a54b14bf15eedbd682bfdc /Year 3/System programming/Practice09/ex3.c
uni-projects-92478827872214a442c96891a607d0781cfa6dd8.tar
uni-projects-92478827872214a442c96891a607d0781cfa6dd8.tar.gz
uni-projects-92478827872214a442c96891a607d0781cfa6dd8.zip
Parent2f8550db96c6d6cb0cb5fe7b448f832a62dcc297 (diff)
[SP/P09] Solved exercises
1 files changed, 46 insertions, 0 deletions
-rw-r--r--Year 3/System programming/Practice09/ex3.c46
diff --git a/Year 3/System programming/Practice09/ex3.c b/Year 3/System programming/Practice09/ex3.c
new file mode 100644
index 0000000..7188491
--- /dev/null
+++ b/Year 3/System programming/Practice09/ex3.c
@@ -0,0 +1,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;
+}