gpt4 book ai didi

c - Linux 上线程 C 程序中的段错误

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:27:00 24 4
gpt4 key购买 nike

我必须为类作业编写一个线程示例。在通过 copy() 创建我的子进程后,我以某种方式遇到了段错误(遗憾的是不得不使用它)。

void thread(void);
#define CLONE_VM 0x00000100
#define ANSWER_TRUE "t"
#define ANSWER_FALSE "f"

static char stack[2];

int main(void) {
void** childThreadBP = NULL;
void** childThread = NULL;

int pid = 0;

puts("create stack for child process...");
void ** new_stack = (void **) malloc(128);
//new_stack = (void **) ((char *)new_stack + 128);

puts("create child process...");
pid = clone(thread, new_stack, CLONE_VM, NULL);

puts("write PID to shared stack...");
stack[0] = (char) pid;

puts("child answered:");
while(1){}
if (stack[1] == ANSWER_TRUE) {
puts("PIDs are equal.");
}
else {
puts("PIDs are NOT equal.");
}
return EXIT_SUCCESS;
}

void thread(void) {
puts("[child]: I'm alive!");
int pidSelf;

pidSelf = getpid();
if (pidSelf == (int)stack[0]) {
puts("[child]: dad the PID you gave me is correct!");
stack[1] = ANSWER_TRUE;
}
else {
puts("[child]: dad the PID you gave me is NOT correct!");
stack[1] = ANSWER_FALSE;
}
}

也许你明白我的错误是什么...... - 代码格式有什么问题?!

我只需要帮助修复段错误 - 其余的应该没问题(我认为;))

问候!!

最佳答案

你有几个问题。首先,正如 Martin James 所说,您需要更大的筹码量。我用的是 16384,效果很好。其次,你需要传入内存空间的顶部,你的行:

new_stack = (void **) ((char *)new_stack + 128); 

很好,取消注释并将其更改为更大的堆栈大小:

void ** new_stack = (void **) malloc(16384);    
new_stack = (void **) ((char *)new_stack + 16384);

第三,您的 PID 存储有问题。堆栈数组必须是整数,因为 pid 可以大于 char 变量可以容纳的值(我的 PID 是 25689)。

这应该可以解决问题。

关于c - Linux 上线程 C 程序中的段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10489753/

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