Ping Pong

Some hints:

  • Add the program to UPROGS in Makefile.

  • You'll need to use the pipe, fork, write, read, and getpid system calls.

  • User programs on xv6 have a limited set of library functions available to them. You can see the list in user/user.h; the source (other than for system calls) is in user/ulib.c, user/printf.c, and user/umalloc.c.

Run the program from the xv6 shell and it should produce the following output:

    $ make qemu
    ...
    init: starting sh
    $ pingpong
    4: received ping
    3: received pong
    $
  

Your program should exchange a byte between two processes and produces output as shown above. Run make grade to check.

#include "kernel/types.h"
#include "kernel/stat.h"
#include "user/user.h"

int main(int argc, char *argv[])
{
	//Create pipe
	int fd[2];
	pipe(fd);

	//fprintf(1, "Create pipe success\n");
	char buf[1];

	//Fork
	if (fork() == 0) {	//child
		if (read(fd[0], buf, 1) == 1)
			fprintf(1, "%d: received ping\n", getpid());
		if (write(fd[1], buf, 1) < 1)
			fprintf(2, "error: child write failed\n");
	} else {
		if (write(fd[1], buf, 1 ) < 1)
			fprintf(2, "error: parent write failed\n");
		if (read(fd[0], buf, 1) == 1)
			fprintf(1, "%d: received pong\n", getpid());
	}

	exit(0);
	
}

Last updated