2013-07-11 47 views
1

我想使用原始克隆系統,但我找不到任何適當的文檔。 我試圖編寫一個小程序來嘗試它,但最終會出現分段錯誤。原始克隆系統調用

我不明白我錯在哪裏。

這裏是小應用:

define STACK_SIZE 0x10000 
define BUFSIZE 200 

#define _GNU_SOURCE 

void hello(){ 
    fprintf(stderr,"Hello word\n"); 
    _exit(0); 
} 


int main() 
{ 

int res; 
void *stack = mmap(0, STACK_SIZE, PROT_READ|PROT_WRITE, 
         MAP_PRIVATE|MAP_ANONYMOUS, -1, 0); 
    pid_t ptid, tid; 

    printf("Stack %p\n", stack + STACK_SIZE); 
    memset(stack, 0, STACK_SIZE); 

    res= syscall(SYS_clone,CLONE_SIGHAND|CLONE_FS|CLONE_VM|CLONE_FILES,stack + STACK_SIZE, &tid,&ptid,NULL); 

    if (!res) 
     hello(); 

    printf("Clone result %x\n", res); 
    waitpid(-1, NULL, __WALL); 

return 0; 
} 
+0

不要使用'clone'系統調用(基本上保留給線程庫實現者)。使用'pthread'庫。 –

+0

我需要使用它,因爲我正在使用系統調用。 –

+0

您還需要'futex'系統調用,它需要一些機器特定的彙編代碼。你應該解釋爲什麼你不能使用pthreads,你應該深入內核源代碼來理解發生的事情。 –

回答

-1

我不能說我建議用克隆去,如果你可以使用並行線程。我對函數有不好的經驗,例如malloc()與克隆有關。

有你看了man page的文檔?

這裏是我運行一個實例。我沒有真正檢查你的代碼,看看它爲什麼會崩潰。

#define _GNU_SOURCE 
#include <stdio.h> 
#include <sched.h> 
#include <sys/types.h> 
#include <sys/wait.h> 
#include <linux/sched.h> 
#include <stdlib.h> 
#include <unistd.h> 
#include <assert.h> 

// Allow us to round to page size 
#define ROUND_UP_TO_MULTIPLE(a,b) \ 
(((a) % (b) == 0) ? (a) : ((a) + ((b) - ((a) % (b))))) 

struct argsy { 
    int threadnum; 
}; 

int fun(void * args) { 
    struct argsy * arguments = (struct argsy *) args; 
    fprintf(stderr, "hey!, i'm thread %d\n", arguments->threadnum); 
    return 0; 
} 

#define N_THREADS 10 
#define PAGESIZE 4096 

struct argsy arguments[N_THREADS]; 

int main() { 
    assert(PAGESIZE==getpagesize()); 

    const int thread_stack_size = 256*PAGESIZE; 
    void * base = malloc((((N_THREADS*thread_stack_size+PAGESIZE)/PAGESIZE)*PAGESIZE)); 
    assert(base); 
    void * stack = (void *)ROUND_UP_TO_MULTIPLE((size_t)(base), PAGESIZE); 

    int i = 0; 
    for (i = 0; i < N_THREADS; i++) { 
     void * args = &arguments[i]; 
     arguments[i].threadnum = i; 
     clone(&fun, stack+((i+1)*thread_stack_size), 
      CLONE_FILES | CLONE_VM, 
      args); 
    } 

    sleep(1); 

    // Wait not implemented 
    return 0; 
} 
+0

這不是一個原始的克隆。 –

+0

也許你可以在這個程序中使用'strace'命令,這樣你就可以看到在這個克隆調用下面的「raw clone」系統調用中有什麼參數。然後看看它和你的通話有什麼不同。 – Macattack