提示:文章写完后,目录可以自动生成,如何生成可参考右边的帮助文档
前言
实现自己在操作系统中的第一个工具,sleep xv6系统中指定的tick数,LAB教程中给了很多提示,也提醒大家多参考已有的代码
提示
- 查看user/中的一些其他程序,了解如何获取传递给程序的命令行参数。如果用户忘记传递参数,sleep将打印错误消息。
- 命令行参数以字符串形式传递;可以使用atoi将其转换为整数(请参见user/ulib.c)。
- 使用系统调用sleep(请参见user/usys.S和kernel/sysproc.c)。
- 确保main调用exit()以退出程序。
- 将程序添加到Makefile中的UPROGS,并通过键入make qemu来编译用户程序。
实现
user/sleep.c
#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 x\n");
exit(1);
}
if(sleep(atoi(argv[1])) < 0){
fprintf(2, "sleep: %s failed to sleep\n", argv[1]);
}
exit(0);
}
Makefile
...
UPROGS=\
$U/_cat\
$U/_echo\
$U/_forktest\
$U/_grep\
$U/_init\
$U/_kill\
$U/_ln\
$U/_ls\
$U/_mkdir\
$U/_rm\
$U/_sh\
$U/_stressfs\
$U/_usertests\
$U/_grind\
$U/_wc\
$U/_zombie\
$U/_sleep\
...
总结
实现了操作系统中第一个程序
$ make qemu
riscv64-unknown-elf-gcc -Wall -Werror -O -fno-omit-frame-pointer -ggdb -gdwarf-2 -MD -mcmodel=medany -ffreestanding -fno-common -nostdlib -mno-relax -I. -fno-stack-protector -fno-pie -no-pie -c -o user/sleep.o user/sleep.c
riscv64-unknown-elf-ld -z max-page-size=4096 -T user/user.ld -o user/_sleep user/sleep.o user/ulib.o user/usys.o user/printf.o user/umalloc.o
riscv64-unknown-elf-objdump -S user/_sleep > user/sleep.asm
riscv64-unknown-elf-objdump -t user/_sleep | sed '1,/SYMBOL TABLE/d; s/ .* / /; /^$/d' > user/sleep.sym
mkfs/mkfs fs.img README user/_cat user/_echo user/_forktest user/_grep user/_init user/_kill user/_ln user/_ls user/_mkdir user/_rm user/_sh user/_stressfs user/_usertests user/_grind user/_wc user/_zombie user/_sleep
nmeta 46 (boot, super, log blocks 30 inode blocks 13, bitmap blocks 1) blocks 1954 total 2000
balloc: first 775 blocks have been allocated
balloc: write bitmap block at sector 45
qemu-system-riscv64 -machine virt -bios none -kernel kernel/kernel -m 128M -smp 3 -nographic -global virtio-mmio.force-legacy=false -drive file=fs.img,if=none,format=raw,id=x0 -device virtio-blk-device,drive=x0,bus=virtio-mmio-bus.0
xv6 kernel is booting
hart 1 starting
hart 2 starting
init: starting sh
$ sleep
Usage: sleep x
$ sleep 10
$