好吧,這是我想要實現的。我希望threadRoutine分叉進程的線程只從特定點開始執行,如註釋//分支進程的線程應從此處開始執行。我使用相同的內存區域來存放原始和分叉的threadRoutine。但我懷疑,既然派生進程的threadRoutine確實執行longjmp的我設置cp_thread 1,它的棧開始從原工藝的threadRoutine了分歧,所以它不能跳,我打算。longjmp從分叉進程
我如何才能解決這個問題,那就是不偏離原來的堆棧和分叉過程threadRoutine在longjmp的的precence的派生進程。
#include <stdio.h>
#include <pthread.h>
#include <stdlib.h>
#include <unistd.h>
#include <setjmp.h>
pthread_attr_t attr;
int cp_thread = 0;
static jmp_buf buf;
pthread_barrier_t bar;
void make_jmp_if_req()
{
if (cp_thread)
longjmp(buf, 1);
}
void *threadRoutine(void *threadMsg)
{
size_t myStackSize;
void *stackAddr;
make_jmp_if_req();
printf("%d: TR:{stackAddr pointer = %lx, @threadRoutine = %lx}\n",
getpid(), stackAddr, threadRoutine);
pthread_attr_getstack(&attr,&stackAddr,&myStackSize);
setjmp(buf);
pthread_barrier_wait(&bar);
printf("%d: TR:stack address %p\n", getpid(), stackAddr);
printf("%d: TR:stack size is %x\n", getpid(), myStackSize);
//printf("%d\n",*((int *)stackAddr)); // <--------------------Causing segmentation fault..
pthread_exit(NULL);
}
int main(int argc, char *argv[])
{
size_t stacksize;
void *stackAddr;
int rc;
size_t i;
pthread_t thread;
pid_t pid;
pthread_attr_init(&attr);
// So that setjmp in the threadRoutine of the orignal process is called before
// longjmp from threadRoutine of the forked process.
pthread_barrier_init(&bar, NULL, 2);
stacksize = 0xC00000; //12582912;
stackAddr = malloc(stacksize);
printf("Main:{stackAddr = %lx}\n", stackAddr);
pthread_attr_setstack(&attr,stackAddr, stacksize);
pthread_attr_getstack(&attr,&stackAddr, &stacksize);
printf("Main:stack address %p\n",stackAddr);
printf("Main:stack size is %x\n",stacksize);
rc = pthread_create(&thread, &attr, threadRoutine, (void*)0);
pthread_barrier_wait(&bar);
switch(pid = fork())
{
case -1:
printf("fork failed");
break;
case 0: // Child
printf("Child pid() = %d\n", getpid());
cp_thread = 1;
rc = pthread_create(&thread, &attr, threadRoutine,(void *)0);
break;
default:// Leader
printf("Parent pid() = %d\n", getpid());
//rc = pthread_create(&thread, &attr, threadRoutine,(void *)0);
}
if(rc)
{
printf("ERROR:return code from pthread_create %d\n",rc);
exit(-1);
}
pthread_exit(NULL);
}
當你說:「所以,請不要說不使用這個,做不同的事情,」你要求人們不回答你的問題。如果你想得到一個有用的答案,告訴我們你真的想要做什麼而不是展示「練習」。 – larsks