Summary Files Commits Branches @commit @diff @stats
path: root / Year 3 / System programming / Practicum5 / ex4.c
diff options
context:
space:
mode:
Commitd4366c2eeb49a37cd50db3962d5489e453a1f18c (patch)
Author
 Syndamia <kamen@syndamia.com>
2023-11-08 13:26:46 +0200
Committer
 Syndamia <kamen@syndamia.com>
2023-11-08 13:26:46 +0200
Files672203edadf385adf5f2b2d0f47ab43abe8f479d /Year 3/System programming/Practicum5/ex4.c
uni-projects-d4366c2eeb49a37cd50db3962d5489e453a1f18c.tar
uni-projects-d4366c2eeb49a37cd50db3962d5489e453a1f18c.tar.gz
uni-projects-d4366c2eeb49a37cd50db3962d5489e453a1f18c.zip
Parentb9d200d296d362b2f3191ac8f2164a0bbc79b2a6 (diff)
[SP/P5] Added solutions to some exercises from today
1 files changed, 41 insertions, 0 deletions
-rw-r--r--Year 3/System programming/Practicum5/ex4.c41
diff --git a/Year 3/System programming/Practicum5/ex4.c b/Year 3/System programming/Practicum5/ex4.c
new file mode 100644
index 0000000..682376d
--- /dev/null
+++ b/Year 3/System programming/Practicum5/ex4.c
@@ -0,0 +1,41 @@
+#include <fcntl.h>
+#include <unistd.h>
+#include <stdio.h>
+#include <sys/wait.h>
+
+int main() {
+ int f1 = open("read.txt", O_RDONLY);
+ if (f1 < 0) {
+ perror("open read.txt");
+ return 1;
+ }
+
+ int f2 = open("write.txt", O_CREAT | O_WRONLY | O_APPEND, 0755);
+ if (f2 < 0) {
+ perror("open write.txt");
+ return 1;
+ }
+
+ pid_t fpid = fork();
+ if (fpid < 0) {
+ perror("fork");
+ return 2;
+ }
+
+ if (fpid == 0) { // child
+ char buff[3];
+ for (int i = 0; i < 6; i++) {
+ read(f1, buff, 3);
+ write(f2, buff, 3);
+ sleep(1);
+ }
+ }
+ else {
+ int status = -2;
+ while (status == -2) {
+ sleep(2);
+ write(f2, "abc", 3);
+ waitpid(fpid, &status, WNOHANG);
+ }
+ }
+}