【问题标题】:Segfault in a threaded C program on LinuxLinux 上的线程 C 程序中的段错误
【发布时间】: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


【解决方案1】:

您有一些问题。首先,正如 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)。

这应该可以解决问题。

【讨论】:

    猜你喜欢
    • 2012-02-21
    • 1970-01-01
    • 1970-01-01
    • 2012-12-23
    • 2018-04-25
    • 2019-07-05
    • 2012-05-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多