gpt4 book ai didi

c - 段错误的原因

转载 作者:太空狗 更新时间:2023-10-29 15:36:58 25 4
gpt4 key购买 nike

我已经使用设置了 CLONE_VM 和 CLONE_FILES 的 clone() 系统调用编写了一个程序。我无法理解为什么输出显示段错误。有人可以更正我的代码并告诉我相同的原因吗。

#include<stdio.h>
#include<unistd.h>
#include<fcntl.h>
#include<sys/types.h>
#include<sys/stat.h>
#include<sched.h>
#include<stdlib.h>

int variable, fd;

int do_something() {
// sleep(100);
variable = 42;
close(fd);
_exit(0);
}

int main(int argc, char *argv[]) {
void **child_stack;
char tempch;

variable = 9;
fd = open("test.file", O_RDONLY);
child_stack = (void **) malloc(16384);
printf("The variable was %d\n", variable);

clone(do_something, child_stack, CLONE_VM|CLONE_FILES, NULL);
// sleep(100);

printf("The variable is now %d\n", variable);
if (read(fd, &tempch, 1) < 1) {
perror("File Read Error");
exit(1);
}
printf("We could read from the file\n");
return 0;
}

最佳答案

您需要知道堆栈在您的处理器上增长的方向,并且您需要知道您必须将堆栈的哪一端传递给 clone()。

来自 man clone:

Stacks grow downwards on all processors that run Linux (except the
HP PA processors), so child_stack usually points to the topmost
address of the memory space set up for the child stack.

没有传递最上面的地址,你传递的是最下面的地址,而且你不在(我猜)HP-PA 上。

修复:

   child_stack = (void **) malloc(16384) + 16384 / sizeof(*child_stack);

附言我对这里明显错误的非答案的数量感到惊讶

  • 否,关闭无效的文件描述符不会在任何 UNIX 上崩溃并且现有 Linux 系统。
  • 不,void*void** 与问题完全无关。
  • 不,您不需要获取 do_something 的地址,编译器会自动为您完成。

最后,是的:在 clone()d 线程中调用 close_exit 或任何其他 libc 例程是 可能不安全,尽管它不会导致这里的问题。

关于c - 段错误的原因,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5255320/

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