gpt4 book ai didi

c - fork 后 main 中的间歇性段错误

转载 作者:可可西里 更新时间:2023-11-01 11:45:08 25 4
gpt4 key购买 nike

我正在上一门关于如何在大学里学习如何在 Linux 上编写多进程程序的类(class)。我仍然很新,正在尽我最大的努力学习,因此欢迎您发现任何错误的地方。

我有一个问题要求我迭代一个数组,主进程的一半,另一半在子进程上。我编写了这样做的代码,但问题是,我注意到如果我运行几次二进制文件,主(父)进程有时会出现段错误。

请查看代码,并告诉我它有什么问题,或者我是否遗漏了此类编程的一个关键方面。我的回答在评论之后开始//answer starts here.

#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <sys/wait.h>
#include <sys/types.h>
#include <unistd.h>

#define ARRAY_SIZE 1000
int main()
{
int numbers[ARRAY_SIZE]; /* array to lookup */
int n; /* the number to find */
time_t t; /* needed to initialize random number generator (RNG) */
int i;

/* intializes RNG (srand():stdlib.h; time(): time.h) */
srand((unsigned)time(&t));

/* initialize array with random numbers (rand(): stdlib.h) */
for (i = 0; i < ARRAY_SIZE; i++)
numbers[i] = rand() % 10000;

/* initialize n */
n = rand() % 10000;


//answer starts here
int half = n / 2;
int count = 0;
int pid_status = 0;
pid_t pid_f = fork();
if (pid_f == -1)
{
return EXIT_FAILURE;
}
else
{
if (pid_f == 0) // child process iterates half end of the array
{
for (i = half; i < ARRAY_SIZE; ++i)
{
if (numbers[i] == n)
{
count++;
}
}
printf("Sons counter:%d\n", count);
exit(count);
} //else it's the father process
else
{
for (i = 0; i < half; ++i)
{
if (numbers[i] == n)
{
count++;
}
}
waitpid(pid_f, &pid_status, 0);
printf("Father counter:%d\n", count);
if (WIFEXITED(pid_status))
{
count += WEXITSTATUS(pid_status);
}
printf("Sum is=%d\n", count);
}
}
return 0;
}

最佳答案

段错误是由于n有时越界导致的:

   n = rand() % 10000;


//answer starts here
int half = n / 2;

一半可以是5000个,但是numbers只有1000个元素。

也许你的意思是:

 n = rand() % 1000;

关于c - fork 后 main 中的间歇性段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48915759/

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