summaryrefslogtreecommitdiff
path: root/user/pingpong.c
diff options
context:
space:
mode:
Diffstat (limited to 'user/pingpong.c')
-rw-r--r--user/pingpong.c72
1 files changed, 32 insertions, 40 deletions
diff --git a/user/pingpong.c b/user/pingpong.c
index 6ed12e7..7b03a76 100644
--- a/user/pingpong.c
+++ b/user/pingpong.c
@@ -1,52 +1,44 @@
#include "kernel/types.h"
-#include "kernel/stat.h"
#include "user/user.h"
-#define N 5
-char buf[N];
+int
+main(int argc, char* argv[])
+{
+ int p[2];
-void
-pong(int *parent_to_child, int *child_to_parent) {
- if (read(parent_to_child[0], buf, N) < 0) {
- printf("read failed\n");
- }
- printf("%d: received %s\n", getpid(), buf);
- if (write(child_to_parent[1], "pong", 4) != 4) {
- printf("write failed\n");
+ if (argc > 1) {
+ fprintf(2, "usage: pingpong\n");
+ exit(1);
}
-}
-void
-ping(int *parent_to_child, int *child_to_parent) {
-
- if (write(parent_to_child[1], "ping", 4) != 4) {
- printf("write failed\n");
- }
- if (read(child_to_parent[0], buf, N) < 0) {
- printf("read failed\n");
- }
- printf("%d: received %s\n", getpid(), buf);
-}
+ pipe(p);
-int
-main(int argc, char *argv[])
-{
- int parent_to_child[2];
- int child_to_parent[2];
+ int pid = fork();
- int pid;
-
- if (pipe(parent_to_child) < 0 || pipe(child_to_parent) < 0) {
- printf("pipe failed\n");
- }
- if ((pid = fork()) < 0) {
- printf("fork failed\n");
- }
if (pid == 0) {
- pong(parent_to_child, child_to_parent);
- } else {
- ping(parent_to_child, child_to_parent);
+ short n;
+ read(p[0], &n, sizeof(n));
+ if (n == 42) {
+ fprintf(1, "%d: received ping\n", getpid());
+ }
+ n++;
+ write(p[1], &n, sizeof(n));
+ close(p[0]);
+ close(p[1]);
+ exit(0);
+ }
+
+ short n = 42;
+
+ write(p[1], &n, sizeof(n));
+ read(p[0], &n, sizeof(n));
+ if (n == 43) {
+ fprintf(1, "%d: received pong\n", getpid());
}
-
+ close(p[0]);
+ close(p[1]);
+
+ wait(0);
+
exit(0);
}