首页 > 解决方案 > 修改子进程中的变量

问题描述

#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
int main() {
 int x = 10;
 pid_t p = fork(), t = fork(), s = fork();
 printf("PID = %d -> pai: %d -> x = %d\n", getpid(), getppid(), x);
 return 0;
}

我对编码真的很陌生,一直在尝试做一些练习,但有一个我做不到

“提议的代码总共生成了 8 个进程,其中 7 个被视为子进程。随着每个子进程将变量增加 2(两个)单位,更改格式代码。”

在此先感谢您,即使您只是花时间阅读它!

标签: c

解决方案


fork()手册页:

返回值 成功时,在父进程中返回子进程的 PID,在子进程中返回 0。失败时,在父进程中返回 -1,不创建子进程,并适当设置 errno。

因此,您应该在每种情况下检查您是在父进程还是子进程中,并相应地进行。

希望这可以帮助!


推荐阅读