gpt4 book ai didi

c - 使用 vfork() 对子级数求和

转载 作者:行者123 更新时间:2023-11-30 15:34:48 26 4
gpt4 key购买 nike

我想用 vfork() 编写一个程序,父级创建 n 个子级,我想用参数插入儿子的数量。然后我想计算儿子的数量,例如:

./sum 4
The sum of the child: 10
The sum of the parent: 10

(1+2+3+4)

这是我想出的小代码,但我得到了无限循环。

int n = atoi(argv[1]);
int i = 1;
pid_t pid;
int sumchild = 0;
int sumparent = 0;

while(i <= n){
pid = vfork();
if(pid == 0){
sumchild = sumchild + i;
}

i++;
}
printf("The sum of the child: %i ", sumchild);

sumparent = (1 + n) * (n / 2);
printf("The sum of the parent: %i \n", sumparent);

我听说你不需要像 fork() 中那样的 wait(),但我不知道为什么这里会出现无限循环。

我应该如何使用vfork()?我写的代码是正确的还是犯了一些错误?

最佳答案

以下代码

    pid = vfork();
if(pid == 0){
sumchild = sumchild + i;

将导致未定义的行为,根据vfork :

The vfork() function has the same effect as fork(2), except that the behavior is undefined if the process created by vfork() either modifies any data other than a variable of type pid_t used to store the return value from vfork(), or returns from the function in which vfork() was called, or calls any other function before successfully calling _exit(2) or one of the exec(3) family of functions.

关于c - 使用 vfork() 对子级数求和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23168279/

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