在 master/slave 上出现分段错误
Getting segmentation fault on master/slave
任何人都可以向我解释为什么我在这段代码上遇到分段错误吗?我一直在努力弄清楚,但在各种搜索中都一无所获。当我 运行 没有调用 main(argc, argv) 的代码时,它 运行s。 Slave 仅将 argv 中的 2 个数字转换为整数,然后 returns 它们。谢谢
#include <stdio.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
int main(int argc, char* argv[])
{
int i;
int* sums;
sums[argc];
pid_t cpid;
int status;
char* args[10];
int count = 1;
for(i = 0; i < (argc / 2); i++) {
cpid = fork();
if(cpid == 0) {
args[1] = argv[count];
args[2] = argv[count + 1];
execvp("./slave", args);
} else {
waitpid(cpid, &status, 0);
sums[i] = WEXITSTATUS(status);
printf("Child returned the number %d\n", sums[i]);
sprintf(argv[i+1], "%d", sums[i]);
}
count += 2;
}
if(sums[0] == 0) {
printf("done\n");
} else {
main(argc/2, args);
}
}
第一个问题是您没有为 sums
分配任何内存并且 sums[i]
访问了一个垃圾位置。这样做:
int sums[argc];
其次,对于execvp
函数参数数组必须有
1. [0] -- 一个合法的字符串。
2.最后一个元素[3]必须为NULL
args[0] = "some-execution-file-name";
args[1] = argv[count];
args[2] = argv[count + 1];
args[3] = NULL;
否则该函数不知道数组的大小,slave 可能会在尝试读取元素 [0] 时死机。
任何人都可以向我解释为什么我在这段代码上遇到分段错误吗?我一直在努力弄清楚,但在各种搜索中都一无所获。当我 运行 没有调用 main(argc, argv) 的代码时,它 运行s。 Slave 仅将 argv 中的 2 个数字转换为整数,然后 returns 它们。谢谢
#include <stdio.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
int main(int argc, char* argv[])
{
int i;
int* sums;
sums[argc];
pid_t cpid;
int status;
char* args[10];
int count = 1;
for(i = 0; i < (argc / 2); i++) {
cpid = fork();
if(cpid == 0) {
args[1] = argv[count];
args[2] = argv[count + 1];
execvp("./slave", args);
} else {
waitpid(cpid, &status, 0);
sums[i] = WEXITSTATUS(status);
printf("Child returned the number %d\n", sums[i]);
sprintf(argv[i+1], "%d", sums[i]);
}
count += 2;
}
if(sums[0] == 0) {
printf("done\n");
} else {
main(argc/2, args);
}
}
第一个问题是您没有为 sums
分配任何内存并且 sums[i]
访问了一个垃圾位置。这样做:
int sums[argc];
其次,对于execvp
函数参数数组必须有
1. [0] -- 一个合法的字符串。
2.最后一个元素[3]必须为NULL
args[0] = "some-execution-file-name";
args[1] = argv[count];
args[2] = argv[count + 1];
args[3] = NULL;
否则该函数不知道数组的大小,slave 可能会在尝试读取元素 [0] 时死机。