【发布时间】:2019-05-30 21:06:19
【问题描述】:
这是一个学校作业,我知道这是一个简单的问题,但对于我的生活,我无法弄清楚我做错了什么。
在父进程中,我需要将 cmdline 参数转换为整数,然后将参数存储在 malloc 数组中。然后我需要一次将每个整数发送给子进程。然后子进程将对从父进程传递的所有整数求和。求和完成后,会将总和返回给父进程。然后父进程打印出总和。
关于这段代码,我有 3 件事不明白。
- 获取命令行参数,将它们转换为整数,并使用指向
malloc数组的指针存储它们。我不明白为什么我不能在我的父进程中写这个:
int* numArray = (int*) malloc (argc * sizeof(int));
for(int i = 0; i < argc; ++i){
numArray[i] = atoi(argv[i+1]);
}
如何将单个值发送到子进程进行求和?我可以一次读取它们,然后将 sum 增加
sumBuf中的值。然后sumBuf被下一个值覆盖,并将 sum 再次增加sumBuf。我该怎么做?如何在父进程中访问子进程的返回值?
将整数存储在malloc 数组中会产生分段错误,我不明白如何纠正这个错误。还有,既然fork返回的是孩子的PID,那么如果孩子返回一个sum,那么sum不应该是孩子的PID吗?
- 对于
malloc数组,我尝试在 for 循环中取消引用numArray,例如:
*numArray[i] = atoi(argv[i+1])
我已尝试在 for 循环中将单个值写入管道
-
我知道fork返回的是child的PID值,那么如果child返回sum,不应该sum=p,把sum存入parent的sum值吗?
int main(int argc, char **argv){ int *numArray = (int*) malloc (argc * sizeof(int)); pid_t p; int fd[2]; pipe(fd); p = fork() //error checks if(p == 0){//child process int sum = 0; int sumBuf = 0; close(fd[1]);//close write end for(int i = 0; i < argc; ++i){ read(fd[0], sumBuf, sizeof(int)); sum += sumBuf; } close(fd[0]);//close read end return sum;//return sum from child process } else{//parent process int sum = 0; close(fd[0]);//close read end for(int i = 0; i < argc; ++i){ numArray[i] = atoi(argv[i+1]); write(fd[1], numArray[i], sizeof(int)); } close(fd[1]);//close write end of pipe sum = p; printf("Sum = %d", sum); return 0; } free(numArray); return 0; }
当我尝试运行此程序时,我收到一条分段错误消息。请不要说我笨,我明白要做什么的想法,但我不明白如何实现它..
【问题讨论】:
-
如果
i == argc -1,那么argv[i+1]是什么? -
当您致电
atoi(argv[argc])时,您预计会发生什么?
标签: c