reijin
reijin

Reputation: 121

Segfault in a threaded C program on Linux

I have to code a thread example for my class homework. Somehow I'm getting a Segfault after creating my child-Process via copy() (have to use that sadly).

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;
}
}

Maybe you see what my mistake is... - what is wrong with the code format?!

I just need help fixing the seg fault - the rest should be ok (I think ;) )

greetings!!

Upvotes: 1

Views: 206

Answers (1)

dag
dag

Reputation: 2218

You have a few issues. The first is as Martin James stated, you need a larger stack size. I used 16384 and that worked fine. Second, you need to pass in the top of the memory space, your line:

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

is fine, uncomment it and change it to the larger stack size:

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

Thirdly, you have an issue with your PID storage. The stack array must be an integer, as the pid can be larger than a char variable can fit (my PID was 25689).

That should fix it up.

Upvotes: 2

Related Questions