gpt4 book ai didi

c - fork 程序请查看

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

编写一个 C 程序,将名为 did 的环境变量设置为 0。

然后,程序将要求用户在循环中输入 5 个数字,并将这些数字存储在由 5 个 int 元素组成的数组中。

  1. 然后程序将创建一个克隆进程(使用 fork())。
  2. 克隆应该运行一个名为 sum() 的函数,该函数计算数组中所有数字的总和。
  3. 之后,克隆会将 did 环境变量设置为 1。它还将创建第二个名为 result 的环境变量,并将其设置为 sum() 函数的返回值。
  4. 父进程等待done变量,直到它被设置为1。
  5. 如果为1,父级将在屏幕上打印:元素之和为:结果。

请注意,结果是名为 result 的环境变量的内容。

请注意,您需要为您的 sum() 函数选择合适的签名,
这意味着由您决定参数的类型和数量以及返回值的类型。

我不确定为什么我的程序无法运行。

#include<stdlib.h>
#include<stdio.h>
#include<string.h>
#include<unistd.h>

int sum(int a[], int size) {

int index, result = 0;

for (index = 0; index < size; index++) {

result+=a[index];
return result;
}
}

int main() {

int i, array[5], result;
long pid;
char string[20];

for (i = 0; i < 5; i++) {

scanf("%d", &array[i]);
if (i == 4) {
}
}

setenv("done", "0", 1);

pid = fork();

if (pid == 0) {

result = sum(array,5);
sprintf(string, "%d", result);
setenv("result", string, 1);
setenv("done","1",1);
}

else {
while (strcmp(getenv("done"), "0") == 0) {
}

result = atoi(getenv("result"));
printf("The sum of elements is %d\n", result);

}

return 0;
}

最佳答案

这不是您想要的答案,但是通过环境变量进行两种方式的通信几乎是不可能的,因为正如评论中指出的那样,子进程无法影响其父进程环境。

我建议您查看inter process communication :

  • 共享内存
  • 管道
  • 套接字
  • RPC

关于c - fork 程序请查看,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59148829/

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