]> Devi Nivas Git - cs3210-lab0.git/commitdiff
Finish part 3
authorAdvaith Menon <noreply-git@bp4k.net>
Thu, 15 Jan 2026 13:33:34 +0000 (19:03 +0530)
committerAdvaith Menon <noreply-git@bp4k.net>
Thu, 15 Jan 2026 13:33:34 +0000 (19:03 +0530)
* Ping Pong

user/src/lab0/pingpong.c

index d98ecf9848b51f155a2d1c1971a9d857dfc81360..82049f12cf44d499891d1145e4b183919cdc3441 100644 (file)
@@ -2,10 +2,53 @@
 #include "stat.h"
 #include "user.h"
 
-int
-main(int argc, char *argv[])
+#define STDOUT_FD 1
+#define READ_END 0
+#define WRITE_END 1
+
+int main(int argc, char *argv[])
 {
-  // Student code goes here
+    // Student code goes here
+    /* child read parent write, parent read child write */
+    /* having 2 pipes allows duplex communication */
+    int crpw[2], prcw[2];
+    int pid;
+    char mypid;
+
+    pipe(crpw); pipe(prcw);
+
+    /* create the two processes */
+    pid = fork();
+
+    /* get the process' PID */
+    mypid = (char) getpid();
+
+    if (pid == 0) {
+        /* child stuff */
+        char parent_pid;
+        /* close ends of pipes that we aren't using */
+        close(prcw[READ_END]); close(crpw[WRITE_END]);
+        /* read data */
+        read(crpw[READ_END], &parent_pid, 1);
+        printf(STDOUT_FD, "parent: received ping from %d\n", (int) parent_pid);
+        /* write data */
+        write(prcw[WRITE_END], &mypid, 1);
+        /* close my write pipe so that my friend doesn't block */
+        close(prcw[WRITE_END]);
+    } else {
+        /* parent stuff */
+        char child_pid;
+        /* close ends of pipes that we aren't using */
+        close(crpw[READ_END]); close(prcw[WRITE_END]);
+        /* write data */
+        write(crpw[WRITE_END], &mypid, 1);
+        wait();
+        /* read data */
+        read(prcw[READ_END], &child_pid, 1);
+        printf(STDOUT_FD, "parent: received pong from %d\n", (int) child_pid);
+        /* close my write pipe so that my friend doesn't block */
+        close(crpw[WRITE_END]);
+    }
 
-  exit();
-}
\ No newline at end of file
+    exit();
+}