【问题标题】:In xv6, how can i make child process run first after fork()?在 xv6 中,如何让子进程在 fork() 之后首先运行?
【发布时间】:2020-08-08 17:39:47
【问题描述】:

我看过很多相关的问题和回复,但是没有人能提供好的解决方案,你能帮帮我吗?

添加:我们可能需要添加一个系统调用来判断是否使用这个命令。

【问题讨论】:

    标签: fork xv6


    【解决方案1】:

    自问自答,多么好笑

    • 首先,添加一个需要整数参数的系统调用int fork_winner(int winner)。如果winner == 1,则子进程首先运行。如果winner == 0,则父级照常首先运行。为此,您可能需要以下帮助:

      1.how do i add a system call / utility in xv6

      2.how to pass a value into a system call function in xv6

    int sys_fork_winner(void)的定义如下,在sysproc.c中:

    int 
    sys_fork_winner(void)
    {
      if(argint(0, &child_first) < 0) // fetch parameter
        return -1;  
      return 0;
    }
    
    • 其次,设置一个全局变量,例如child_first,保存winner的值。

    • 第三,修改fork()中的proc.c。如果winner == 1,则在创建子进程后调用yield()。否则,什么也不做。

    • 最后,您可能需要一个用户程序来测试它是否工作。核心代码如下:

    void test(){
        int i = 0;   
        int ret = 0;
     for (i = 0; i < TOTAL_TEST_TRIALS; i++)
        {
            printf(1, "\nTrial %d: ", i);
            ret = fork();
            if (ret < 0)
            {
                printf(1, "fork() failed (%d)\n", ret);
                exit();
            }
            else if (ret == 0) // child
            {
                printf(1, " child! ");
                exit();
            }
    
            // parent
            printf(1, " parent! ");
            if (ret != wait())
            {
                printf(1, "wait() failed!\n");
            }
        }
    
        printf(1, "\n");
    }
    
    int
    main(int argc, char *argv[])
    {
    
    
        printf(1,"Fork test\nSet child as winner");
    
        fork_winner(1);  
        test();
    
        printf(1,"\nSet parent as winner");
        fork_winner(0);//the default
        test();
    
    
        exit();
    }
    

    这个article可以帮助你在xv6中添加一个用户程序。

    感谢您的宝贵时间!

    【讨论】:

    • 你能发布你的新系统调用吗?此外,我认为您不需要使用全局变量,您可以选择在fork_winner中调用yield()
    • 在我的例子中,系统调用用于传递测试程序中函数fork_winner()所需的参数。 fork_winner() 的代码已放入其中,child_first 是全局变量。
    猜你喜欢
    • 1970-01-01
    • 2013-08-18
    • 2016-02-09
    • 2017-11-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-07-04
    相关资源
    最近更新 更多