所以我正在进行一项任务,用户只需调用parent.c类,例如" ./ parent 1 2 3 4 5 6 7 8"而child.c类将计算结果的总和。
通过阅读这两行中的2个数字来工作...... " 1 + 2" " 3 + 4" " 5 + 6" " 7 + 8"
我已经成功地做到了这一点,但是当输入最终变成奇数时,我碰到了一堵完整的砖墙。当我继续循环子进程时,每个2个数字将不断加起来,但是当循环到达输入的末尾并且不再有2个数字要添加时它变成一个问题,而只是一个(奇数情形)。
所以如果输入成为诸如... " ./ parent 1 2 3 4 5 6 7"或" ./ parent 1 2 3"
它只会将返回归为0。
我的文件将计算偶数,但不会累加奇数。我想要实现的总体目标是,如果输入达到奇数,就能够添加零。我有一个尝试的解决方案是,如果数据数组中的值的数量是奇数,则在while循环的开头检查,然后将index递增1,然后将0添加到该索引。但它仍然没有提供正确的解决方案。
parent.c
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <math.h>
int main(int argc, char *argv[])
{
int status, workerid, id;
int i = 0;
int loopcount = 0;
char* data[argc];
for(i = 1; i <= argc; i++)
{
data[i] = argv[i];
}
int numberloops = argc / 2;
int index = 0;
while(numberloops > index)
{
loopcount = 0;
for(i = 1; i <= argc; i += 2)
{
loopcount++;
id = fork();
if(id < 0)
{
perror("fork() ERROR.\n");
}
else if(id > 0)
{
workerid = waitpid(id, &status, 0);
status = WEXITSTATUS(status);
//update data array
char* statStr;
statStr = (char*) malloc(16);
snprintf(statStr, sizeof(statStr), "%d", status);
data[loopcount] = statStr;
}
else
{
execlp("./child", "child", data[i], data[i+1], NULL);
}
}
int arrayNum = atoi(data[loopcount]);
// Adds a 0 to the array.
while(loopcount < argc)
{
loopcount++;
data[loopcount] = 0;
}
//change argc (number of values in data array)
if(argc % 2 == 1)
{
argc = (argc + 1) / 2;
}
else
{
argc /= 2;
}
index++;
}
printf("Final Sum: %s.\n\n", data[1]);
}
child.c
#include<stdio.h>
#include<stdlib.h>
int main(int argc, char *argv[])
{
int x = atoi(argv[1]);
int y = atoi(argv[2]);
int sum = x + y;
printf("%d + %d = %d Worker PID: %d\n", x, y, sum, getpid());
exit(sum);
}
答案 0 :(得分:0)
要解决“odd
- 问题”,一个简单的方法是定义char * data[argc + 1];
并在将相关元素设置为点之前初始化其所有元素以指向文字"0"
到argv
的元素。
答案 1 :(得分:0)
在我看来,你使代码比需要复杂得多。一些具体项目:
1)为什么你有两个嵌套循环(即while
里面有for
?据我所知,这只会引发过多child
2)workerid
似乎未使用!?
3)arrayNum
似乎未使用!?
4)为什么要将返回值转换为字符串?你想计算一个总和,所以只需将它保持为整数
简化代码可以提供类似的内容:
#include <stdio.h>
#include <unistd.h>
#include <sys/wait.h>
int main(int argc, char *argv[])
{
int status, id;
int i = 1;
int sum = 0;
int numberloops = argc / 2;
int index = 0;
while(numberloops > index)
{
id = fork();
if(id < 0)
{
perror("fork() ERROR.\n");
}
else if(id > 0)
{
waitpid(id, &status, 0);
status = WEXITSTATUS(status);
sum += status;
}
else
{
if (i == argc-1)
{
execlp("./child", "child", argv[i], "", NULL);
}
else
{
execlp("./child", "child", argv[i], argv[i+1], NULL);
}
}
i = i + 2;
index++;
}
printf("Final Sum: %d.\n\n", sum);
}
示例:
./parent 1 2 3 4 5
1 + 2 = 3 Worker PID: 12961
3 + 4 = 7 Worker PID: 12962
5 + 0 = 5 Worker PID: 12963
Final Sum: 15.