2015-02-06 71 views
0

我試圖用fork的幫助來打印一個數組,其中每個元素都將由一個單獨的子進程打印。用fork()打印數組

void printArray_fork(int *p_array, int length){ 
    int i; 

    pid_t pid; 
    for(i = 0; i<length;i++){ 
     /* Create children procs */ 
     pid = fork(); 
     if(pid==0){ 
      break; 
     } 
    } 

    if(pid == 0) { 
      printf("My process ID : %d value: %d\n",getpid(),*(p_array + i)); 
    } 
} 

現在的問題是,我希望它也是爲了(升序或降序,無所謂)我該怎麼做?

+1

'fork'不打印數組。它創建一個新的過程。你需要在父進程中「waitpid」。 – 2015-02-06 06:46:33

回答

0

這裏稍微修改一下您的代碼以便按順序打印。

/* Create children procs */ 
    pid = fork(); 
    wait(); 

如上所述,您只需要使用等待創建下一個子進程。