mit-6.s081-2020 | Lab1 Utilities
2022-10-10 13:22:06
本文总阅读量

info

MIT 6.S801 xv6 book 2020版 中文翻译

https://zhuanlan.zhihu.com/p/272199762

https://fanxiao.tech/posts/MIT-6S081-notes/#16-lab-1-unix-utilities

sleep (easy)

code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#include "kernel/types.h"
#include "kernel/stat.h"
#include "user/user.h"

int main(int argc, char *argv[]) {

if (argc < 2) {
fprintf(2, "Usage: sleep <sleepNum>... \n");
exit(1);
}

int sleepNum = atoi(argv[1]);
if (sleepNum < 0) {
fprintf(2, "Negative sleep num, invalid! \n");
exit(1);
}

sleep(sleepNum);
exit(0);

}

pingpong (easy)

info

关于为什么需要close()

code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
#include "kernel/types.h"
#include "kernel/stat.h"
#include "user/user.h"


int main(int argc, char *agrv[]) {

// 管道是单向通信的。所以当需要在两个进程之间通信的时,需要一个关闭读端也就是p[0],
// 一个关闭写端也就是p[1]
int p_parent_to_child[2];
int p_child_to_parent[2];
pipe(p_parent_to_child);
pipe(p_child_to_parent);

char buf[5];

int pid = fork();
if (pid == 0) {
close(p_parent_to_child[1]); // 关闭写端
read(p_parent_to_child[0], buf, 4);
printf("%d: received %s\n", getpid(), buf);
close(p_child_to_parent[0]);
write(p_child_to_parent[1], "pong", 4);
} else {
close(p_parent_to_child[0]);
write(p_parent_to_child[1], "ping", 4);
close(p_child_to_parent[1]);
read(p_child_to_parent[0], buf, 4);
printf("%d: received %s\n", getpid(), buf);
}

exit(0);

}

primes (moderate)/(hard)

info

贝尔实验室与 CSP 线程

code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
#include "kernel/types.h"
#include "kernel/stat.h"
#include "user/user.h"
#include <stdbool.h>

#define N 36

int main(int argc, char *argv[]) {

int nums[N];
for (int i = 0; i < N; i++) {
nums[i] = i;
}

while (true) {
int p[2];
pipe(p);
int pid = fork();
if (pid > 0) { // 父进程往管道里面写数据
close(p[0]);
int writebuf[N];
int cnt = 0;
for (int i = 2; i <= 35; i++) {
if (nums[i] != 0) {
writebuf[cnt++] = i;
write(p[1], &writebuf[cnt - 1], sizeof writebuf[cnt - 1]);
}
}
close(p[1]);
wait(0);
exit(0);
} else { // 子进程从管道里面读数据
close(p[1]);
int prime = 0;
if (read(p[0], &prime, sizeof prime) == 0) {
exit(0);
}
printf("prime %d\n", prime);
for (int i = prime; i <= 35; i += prime) {
nums[i] = 0;
}
close(p[0]);
}
}

exit(0);

}

find (moderate)

info

The C library function void memmove(void str1, const void *str2, size_t n) copies n characters from str2 to str1, but for overlapping memory blocks, memmove() is a safer approach than memcpy().

1
void *memmove(void *str1, const void *str2, size_t n)

上一页
2022-10-10 13:22:06
下一页