Write a user-level program that uses xv6 system calls to ''ping-pong'' a byte between two processes over a pair of pipes, one for each direction. The parent should send a byte to the child; the child should print "<pid>: received ping", where <pid> is its process ID, write the byte on the pipe to the parent, and exit; the parent should read the byte from the child, print "<pid>: received pong", and exit. Your solution should be in the file user/pingpong.c.
#include "kernel/types.h"
#include "kernel/stat.h"
#include "user/user.h"
int main(){
int p[2];
char buf[10] = {0,};
pipe(p);
if(fork() > 0) { // parent side
write(p[1], "ping\0", 5);
wait(0);
if(read(p[0], buf, 5) != 5){
fprintf(2, "%d(Parent): Error occurred while reading\n", getpid());
exit(1);
}
printf("%d: received %s\n", getpid(), buf);
close(p[0]);
close(p[1]);
exit(0);
}
else { // child side
if(read(p[0], buf, 5) != 5){
fprintf(2, "%d(Child): Error occurred while reading\n", getpid());
exit(1);
}
printf("%d: received %s\n", getpid(), buf);
write(p[1], "pong\0", 5);
close(p[0]);
close(p[1]);
exit(0);
}
}
'xv6:2024 > Chapter 1' 카테고리의 다른 글
Exercise 1-5. xargs (1) | 2024.11.19 |
---|---|
Exercise 1-4. find (0) | 2024.11.18 |
Exercise 1-3. primes (0) | 2024.11.16 |
Exercise 1-1. sleep (0) | 2024.11.16 |
xv6's every system call && read() from the pipe (1) | 2024.11.16 |