Can the order of execution of fork() be determined?

前端 未结 5 1716
温柔的废话
温柔的废话 2020-11-28 13:33

I\'m working on an exercise on the textbook \"Operating System Concepts 7th Edition\", and I\'m a bit confused about how does fork() work. From my understanding

5条回答
  •  被撕碎了的回忆
    2020-11-28 14:11

    You are asking many questions, I'll try to answer them in a convenient order.

    First question

    To be honest, I don't see any difference between using fork and not using fork.

    That's because the example is not a very good one. In your example the parent doesn't do anything so the fork is useless.

    Second

    else {
        // what do we need to do here? 
    }
    

    You need to wait(2) for the child to terminate. Make sure you read that page carefully.

    Third

    I want the parent process to handle the input from user, and let the child process handle the display

    Read the input before the fork and "handle" the display inside if (pid == 0)

    Fourth

    But then, how do we know exactly which process runs first?

    Very few programs should concern themselves with this. You can't know the order of execution, it's entirely dependent on the environment. TLPI says this:

    After a fork(), it is indeterminate which process—the parent or the child—next has access to the CPU. On a multiprocessor system, they may both simultaneously get access to a CPU.

    Applications that implicitly or explicitly rely on a particular sequence of execution in order to achieve correct results are open to failure due to race conditions

    That said, an operating system can allow you to control this order. For instance, Linux has /proc/sys/kernel/sched_child_runs_first.

提交回复
热议问题