MIT6.S081学习总结-lab1: Xv6 and Unix utilities

最近学习MIT比较有名的操作系统课程6.S081,这门课程主要亮点就是设计精巧的lab了。这里记录一下lab1:Xv6 and Unix utilities.

1.sleep

用系统调用实现sleep

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

int
main(int argc, char* argv[])
{
   
    if (argc <= 1) {
   
        fprintf(2, "sleep: missing operand\n");
        exit(1);
    }
    int i;
    for (i = 1; i < argc; ++i) {
   
        int t = atoi(argv[i]);
        sleep(t);
    }
    exit(0);
}

2.pingpong

父子进程用管道通信,父进程发一个字节给子进程,子进程收到输出pid: received ping,然后发送一个字节给父进程,父进程收到后输出pid: received pong
用两个管道即可

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

int 
main(int argc, char* argv[])
{
   
    int pipe1[2];
    int pipe2[2];
    pipe(pipe1);
    pipe(pipe2);
    int pid = fork();
    if (pid == 0) {
     // child
        close(pipe1[1]);
        close(pipe2[0]);
        int childPid = getpid();
        char buf[8];
        int n = read(pipe1[0], buf, 8);
        if (n > 0) {
   
            fprintf(1, "%d: received ping\n", childPid);
            write(pipe2[1], "0", 1);
        }
        close(pipe1[0]);
        close(pipe2[1]);
    } else {
   
        close(pipe1[0]);
        close(pipe2[1])

你可能感兴趣的:(Linux,操作系统,6.S081,linux)