2009-02-28 49 views
0

假設所有的變量先前都被聲明過...因爲它們已經被使用過了。子進程不打印任何使我認爲它沒有被執行的東西。父進程運行良好,儘管它沒有獲得共享內存。 我對此代碼的長度表示歉意...爲什麼孩子在這裏過程不打印任何東西?

// create 5 child process 
for(int k=0;k<5;k++){ 

    // fork a child process 
    pid = fork(); 

    // error occured on fork 
    if (pid < 0) { 
     fprintf(stderr, "Fork Failed"); 
     return 1; 
    } 
    // this is what the child process will run 
    else if (pid == 0) { 
     //create a shared mem segment 
     segment_id = shmget(IPC_PRIVATE, size, S_IRUSR | S_IWUSR); 

     //attach the shared memory segment 
     shared_memory = (char *) shmat(segment_id, NULL, 0); 

     printf("this is child"); 

     double x = 0; 
     double sum = 0; 

     // Run process that sums the function 
     for(int i=0; i<n; i++){ 
      // get random number in range of x1-x2 
      x = rand()%(x2 - x1 + 1) + x1; 
      sum = sum + f(x); 
     } 

     //write output to the shared memory segment 
     sprintf(shared_memory, "%f", sum); 
     execlp("/bin/ls", "ls", NULL); 

    } 

    // this is what the parent process will run 
    else { 

     //print output from shared memory 
     printf("\n*%s", shared_memory); 

     //detach shared memory 
     shmdt(shared_memory); 

     //Here we add the shared memory to the array 
     // To add together at the end 
     // but since I cant get the memory to share 
     // the array can't be implemented 

     //remove the shared memory segment 
     shmctl(segment_id, IPC_RMID, NULL); 

     wait(NULL); 
    } 
} // End of for statement 
+0

您不檢查shm *操作的任何錯誤條件。 – 2009-02-28 01:35:32

回答

10

C stdout流在內部緩衝數據。很可能您的「這是孩子」消息正在被緩衝,緩衝區沒有被execlp刷新,所以它就會消失。試試fflush(stdout);在printf之後。順便提一句,你應該在fork()之前這樣做,這樣子和父都不會嘗試寫入從fork之前緩衝的輸出。

+0

由於打印輸出不包含換行符,因此成爲問題的可能性很大。如果輸出是行緩衝的,則換行會強制數據出現。 – 2009-02-28 01:39:08

-1

先去掉所有的共享內存,然後看看子進程是否可以成功printf。

從該片段看,您正在初始化子進程中的shared_memory,但不是在父進程中。

3

打印到stderr它沒有被緩衝。

fprintf(stderr,"Plop\n"); 

此外共享存儲器的東西(SEGMENT_ID,shared_memory)在父未初始化(或者如果它是那麼它是不一樣的孩子)。

此外,父母可能會在孩子仍在處理時摧毀共享內存的東西。家長應該先等待,然後處理孩子生成的數據。

相關問題