【问题标题】:Fork() process behaviourfork() 进程行为
【发布时间】:2017-06-27 03:35:12
【问题描述】:

假设我有一段代码

#include<stdio.h>
#include<unistd.h>
#include<sys/types.h>

int main()
{
    pid_t p ; 
    p = fork (); // p is a new process
    // three cases -1, 0 , >0 
    // -1 will report the error 
    //  0 will tell us that the process is created 
    int i =0 ;
    switch(p)
    {
    case -1 : printf("Error; \n");
              break;

    case 0: printf("I am child and my pid is %d",getpid());
            printf("\nMy parent pid is : %d\n",getppid());
            break;

    default:printf("You are inside parent whose pid is %d\n",getpid());  
            for (int i =20 ; i <= 29; i++)
            {
                printf("%d\n",i);
            }
            break;
    }
}

此代码在不同的操作系统中给出不同的输出。我的系统上有 Ubuntu 14.04,我们大学实验室的操作系统是 Red Hat,当我们在不同的机器上执行相同的程序时,输出是不同的。 输出就像(在我的系统上):

You are inside parent whose pid is 5283
20
21
22
23
24
25
26
27
28
29
I am child and my pid is 5284
My parent pid is : 5283

实验室内部的系统给出的输出类似于

I am child and my pid is 5284
My parent pid is : 5283
You are inside parent whose pid is 5283
20
21
22
23
24
25
26
27
28
29

如果我们仔细检查程序,在我系统的输出中,父进程首先完成任务,然后将控制权交给子进程,而在另一个系统上,父进程首先创建子进程,子进程首先执行它任务,然后恢复到父级。那么有什么区别呢?它是否取决于系统架构或任何其他参数,如操作系统。请告诉我们

【问题讨论】:

  • 简而言之,它们执行的相对顺序无话可说。这取决于调度程序所依赖的调度算法。通常,许多算法会赋予子进程更高的优先级,因为在大多数情况下,创建子进程是为了运行不同的程序,因此如果父进程先运行,则不会为父进程复制页面...

标签: fork


【解决方案1】:

它只取决于系统的调度程序。如果您在同一台机器上多次启动程序,结果可能会有所不同。

一旦两个进程同时启动,就不能假定它们的指令之间的执行顺序。

【讨论】:

    猜你喜欢
    • 2019-02-22
    • 1970-01-01
    • 1970-01-01
    • 2014-06-17
    • 2015-04-28
    • 2012-01-14
    • 2011-06-27
    • 2020-08-17
    • 1970-01-01
    相关资源
    最近更新 更多