Reputation: 2420
I'm trying to create a custom pthread library using context switching in C. I've run into this problem of getting segmentation faults when I call setcontext() - there seems to be limited documentation on this function so I can't really figure out what's going on, and it's already cost me a lot of downtime. My code:
#include <signal.h>
#include <ucontext.h>
struct mypthread_t{
int id;
int pid;
int isRunning;
mypthread_t *next;
ucontext_t* context;
};
int mypthread_create(mypthread_t *thread, const mypthread_attr_t *attr, void *(*start_routine)(void *), void *arg)
{
printf("Hello\n");
thread->id = threadID++;
thread->context = malloc(sizeof(ucontext_t));
thread->context->uc_stack.ss_sp = malloc(16384);
thread->context->uc_stack.ss_size = 16384;
thread->context->uc_link = 0;
makecontext(thread->context, (void *) start_routine, 1, arg);
setcontext(thread->context);
}
It seems like I've malloc'd everything that needs to be malloc'd, so I don't understand why setcontext(thread->context) is giving me a segfault. Any help would be appreciated - the context family of functions is really stumping me. Here's the line it fails at from gdb:
fldenv (%rcx)
Upvotes: 3
Views: 2127
Reputation: 1262
Initialize your ucontext_t
object with a call to getcontext(3)
before calling makecontext(3)
:
if (getcontext(thread->context) == -1) {
// ... error handling
// ... errno is set appropriately to indicate the error that occurred
}
makecontext(...);
Upvotes: 3