gpt4 book ai didi

c - fork()执行过程

转载 作者:太空狗 更新时间:2023-10-29 17:18:44 26 4
gpt4 key购买 nike

fork() 究竟是如何工作的?

下面的代码

#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

Argument 1 is hello

Forked in for loop increment 1

Argument 2 is world

Forked in for loop increment 2

Forked in for loop increment 1

Argument 2 is world

Forked in for loop increment 2

Forked in for loop increment 2

fork一般先执行什么代码。我想知道 fork() 的原理,而不是仅仅基于这个例子。我本可以在命令行上使用多个参数。

最佳答案

fork 是一个系统调用,即调用内核的库例程。为 fork 调用提供服务时,内核会创建一个新进程,该进程执行与调用它的进程相同的程序。新进程开始执行,就好像调用了fork;返回值与parent中的不同,可以区分两者。

调用 fork 的常用习惯用法是:

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();
}

如何这是如何工作的:操作系统对调用 fork 的进程进行了近乎完美的复制(PID 和其他一些值不同,但内存内容开始输出几乎相同,并且通常在两者中打开相同的文件)。复制通常使用所谓的写时复制 (COW) 语义完成,因此在其中一个进程开始分配给变量之前,几乎没有任何实际复制完成。

关于c - fork()执行过程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5010359/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com