fork()的执行过程 [英] fork() execution process

查看:269
本文介绍了fork()的执行过程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

究竟如何fork()的工作?

How exactly does fork() work?

以下code

#include <stdio.h>

int main (int argc, char const *argv[])
{
printf("Hi\n");
int i;
for(i = 1; i < argc; i++)
{
    printf("Argument %d is %s\n", i, argv[i]);
    fork();
    printf("Forked in for loop increment %d\n", i);
}


return 0;
}

给出以下输出

/a.out的Hello World

/a.out hello world

参数1为hello

在分叉的循环增量1

参数2是世界

在分叉的循环增量2

在分叉的循环增量1

参数2是世界

在分叉的循环增量2

在分叉的循环增量2

什么code不执行叉首先,在一般。我想知道叉(的原则),而不是仅仅基于这一个例子。我本来可以在命令行上多个参数。

What code does fork execute first, in general. I would like to know the principles of fork() rather than based on just this one example. I could have had multiple arguments on the command line.

推荐答案

是一个系统调用,即库函数调用到内核。当维修一个呼叫时,内核创建一个新的进程,执行相同的程序作为调用它的过程。新进​​程开始执行,如果的的呼吁;返回值是从一个在父母不同,这样就可以区分这两个。

fork is a system call, i.e. a library routine that calls into the kernel. When servicing a fork call, the kernel creates a new process that executes the same program as the process that called it. The new process starts executing as if it had called fork; the return value is different from the one in the parent, so you can distinguish the two.

用于调用常见的成语是:

The common idiom for invoking fork is:

pid_t pid = fork();

switch (pid) {
  case -1:
    /* an error occurred, i.e. no child process created */
    handle_error();
  case 0:
    /* a return value of 0 means we're in the child process */
    do_child_stuff();
    break;  // or _exit()
  default:
    /* we're in the parent; pid is the child's process id */
    do_parent_stuff();
}

如何的工作原理是:操作系统使过程调用的一个近乎完美的复制(PID和一些其他的值是不同的,但存储器内容开始时几乎相同,并且通常在同一文件中都打开)。该副本使用所谓的写入时复制(COW)的语义常见的做,所以很难有做过任何实际的复制,直到进程中的一个开始分配给变量。

How this works is: the OS makes a near-perfect copy of the process calling fork (the PID and some other values are different, but the memory contents start out practically the same and usually the same files are opened in both). The copy is commonly done using so-called copy-on-write (COW) semantics, so there's hardly any actual copying done until one of the processes starts assigning to variables.

这篇关于fork()的执行过程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆