Summary Files Commits Branches @commit @diff @stats
path: root / Year 3 / System programming / Practicum5 / ex2.c
diff options
context:
space:
mode:
1 files changed, 54 insertions, 0 deletions
-rw-r--r--Year 3/System programming/Practicum5/ex2.c54
diff --git a/Year 3/System programming/Practicum5/ex2.c b/Year 3/System programming/Practicum5/ex2.c
new file mode 100644
index 0000000..88b337c
--- /dev/null
+++ b/Year 3/System programming/Practicum5/ex2.c
@@ -0,0 +1,54 @@
+#include <sys/types.h>
+#include <fcntl.h>
+#include <unistd.h>
+#include <stdio.h>
+#include <stdlib.h>
+
+int main() {
+ int f = open("test.txt", O_CREAT | O_WRONLY | O_TRUNC, 0755);
+ if (f < 0) {
+ perror("open test.txt");
+ return 2;
+ }
+
+ pid_t fpid = fork();
+
+ if (fpid < 0) {
+ perror("fork");
+ return 1;
+ }
+
+ if (fpid == 0) { // in child
+ sleep(2);
+ int ws = write(f, "From Child 1\n", 13);
+
+ if (ws < 0) {
+ perror("write from child");
+ return 3;
+ }
+
+ sleep(5);
+ ws = write(f, "From Child 2\n", 13);
+
+ if (ws < 0) {
+ perror("write from child");
+ return 3;
+ }
+ }
+ else {
+ int ws = write(f, "From Parent 1\n", 14);
+
+ if (ws < 0) {
+ perror("write from child");
+ return 3;
+ }
+
+ sleep(3);
+ ws = write(f, "From Parent 2\n", 14);
+
+ if (ws < 0) {
+ perror("write from child");
+ return 3;
+ }
+ }
+}