Home > Blockchain >  Why return does not exit a process in xv6?
Why return does not exit a process in xv6?

Time:03-24

Here is my code for user/sleep.c:

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

int
main(int argc, char *argv[])
{
        if (argc < 2)
        {
                printf("You have forgotten to pass an argument.");
                exit(1);
        }
        int arg = atoi(argv[1]);
        sleep(arg);
        exit(0);
        // return 0;
}

All is fine but with the return 0 instead of exit(0), I get the following error:

usertrap(): unexpected scause 0x000000000000000d pid=4
            sepc=0x00000000000000f6 stval=0x0000000000003008

Why is that?

CodePudding user response:

It's because xv6 is not standard on this point:  

see https://tnallen.people.clemson.edu/2019/03/04/intro-to-xv6.html

Returning after main is a special case that is not supported in XV6, so just remember to always exit() at the end of main instead of return. Otherwise, you will get a “trap 14,” which in this case is XV6-speak for “Segmentation Fault.” Finally, notice that our headers are different. There is no #include <stdio.h> as you might be used to. Again, this is because the standard library is different. Check out these headers to see what kind of user utilities you have available.


So why did we need exit() in xv6?

Because, when building a program with gcc for linux for instance, the tool chain add the required exit call: see https://en.wikipedia.org/wiki/Crt0

In short, on linux, your program don't start at main but at start:

void start(void) {
    /* get argc, argv, env) */

    int r = main(argc, argv, envp);  /*  << start calls the actual main */

    exit(r);
}

On xv6, on contrary, the real starting point is main when OS try to return from main, it has no address to pop what cause a seqfault

  •  Tags:  
  • c xv6
  • Related