* same with xv6
[mascara-docs.git] / i386 / MIT / course / src / git.lab / user / testfdsharing.c
blobe3bf025c116501487cbcdd0e6e715c5f720665a1
1 #include <inc/x86.h>
2 #include <inc/lib.h>
4 char buf[512], buf2[512];
6 void
7 umain(int argc, char **argv)
9 int fd, r, n, n2;
11 if ((fd = open("motd", O_RDONLY)) < 0)
12 panic("open motd: %e", fd);
13 seek(fd, 0);
14 if ((n = readn(fd, buf, sizeof buf)) <= 0)
15 panic("readn: %e", n);
17 if ((r = fork()) < 0)
18 panic("fork: %e", r);
19 if (r == 0) {
20 seek(fd, 0);
21 cprintf("going to read in child (might page fault if your sharing is buggy)\n");
22 if ((n2 = readn(fd, buf2, sizeof buf2)) != n)
23 panic("read in parent got %d, read in child got %d", n, n2);
24 if (memcmp(buf, buf2, n) != 0)
25 panic("read in parent got different bytes from read in child");
26 cprintf("read in child succeeded\n");
27 seek(fd, 0);
28 close(fd);
29 exit();
31 wait(r);
32 if ((n2 = readn(fd, buf2, sizeof buf2)) != n)
33 panic("read in parent got %d, then got %d", n, n2);
34 cprintf("read in parent succeeded\n");
35 close(fd);
37 if ((fd = open("newmotd", O_RDWR)) < 0)
38 panic("open newmotd: %e", fd);
39 seek(fd, 0);
40 if ((n = write(fd, "hello", 5)) != 5)
41 panic("write: %e", n);
43 if ((r = fork()) < 0)
44 panic("fork: %e", r);
45 if (r == 0) {
46 seek(fd, 0);
47 cprintf("going to write in child\n");
48 if ((n = write(fd, "world", 5)) != 5)
49 panic("write in child: %e", n);
50 cprintf("write in child finished\n");
51 close(fd);
52 exit();
54 wait(r);
55 seek(fd, 0);
56 if ((n = readn(fd, buf, 5)) != 5)
57 panic("readn: %e", n);
58 buf[5] = 0;
59 if (strcmp(buf, "hello") == 0)
60 cprintf("write to file failed; got old data\n");
61 else if (strcmp(buf, "world") == 0)
62 cprintf("write to file succeeded\n");
63 else
64 cprintf("write to file failed; got %s\n", buf);
66 breakpoint();