【发布时间】:2012-05-07 22:00:06
【问题描述】:
我必须为我的课堂作业编写一个线程示例。在通过 copy() 创建子进程后,不知何故我遇到了 Segfault (不得不遗憾地使用它)。
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;
}
}
也许你明白我的错误是什么...... - 代码格式有什么问题?!
我只需要帮助修复 seg 错误 - 其余的应该没问题(我认为 ;))
你好!!
【问题讨论】:
-
你为什么使用
clone(2)而不是pthreads库? -
@AdamRosenfield:因为我们必须...:/
-
@MartinJames:遗憾的是,没有让它变得更好......
-
代码编译并为我工作,没有段错误,但说:
[child]: dad the PID you gave me is NOT correct! -
您正在向
clone系统调用传递一个指向堆栈末尾的指针,但它需要一个指向开头的指针。
标签: c linux multithreading segmentation-fault