2012-03-29 19 views
0

我試圖點產品兩個向量,每個進程採取單獨的開始和結束索引。似乎正在發生的是代碼被執行兩次。叉子和父母運行單獨的代碼

void DotProduct::MultiProcessDot() 
    { 
    pid_t pID,w; 
    int status; 
    unsigned int index = mNumberOfValuesPerVector/2; 

    if((pID = fork()) < 0){ 
     cout << "fork error" << endl; 
    } 
    else if(pID == 0){ /* child */ 
     ProcessDotOperation(0, index); 
     exit(EXIT_FAILURE); 
    } 
    else{ /* parent */ 
     ProcessDotOperation(index, mNumberOfValuesPerVector); 
     w = waitpid(pID, &status, WNOHANG); 
     if(w == 0){ 
      cout << "alive" << endl; 
     }else if(w == -1){ 
      cout << "dead" << endl; 
     } 
    } 
} 

ProcessDotOperation計算使用共享存儲器與sem_wait()sem_post()點積。什麼似乎發生是這樣的:

  • 父運行ProcessDotOperation

  • 「活着」 打印

  • 父運行ProcessDotOperation

  • 「活着」 打印

  • 程序繼續執行(繼續執行其他功能)

  • 兒童運行ProcessDotOperation

  • 兒童運行ProcessDotOperation

注:我可能會發生的事情的一個根本性的誤解,因此通過parentchild,我指的是在評論關於我認爲正在運行哪個進程的代碼。

我該如何讓孩子運行一次ProcessDotOperation一次,父母運行ProcessDotOperation一次,然後程序繼續運行?

任何幫助表示讚賞。

編輯

如果我的fork()之前打印,並更改w = waitpid(pID, &status, WNOHANG);w = waitpid(pID, &status, 0);,這裏的輸出:

分叉

孩子

分叉

孩子

繼續執行...

這裏是ProcessDotOperation代碼:

void DotProduct::ProcessDotOperation(unsigned int startIndex, unsigned int endIndex) 
{ 

    for(unsigned int i = startIndex; i < endIndex; i++){ 
     sem_wait(mSem); 

     mShmProductId += mVectors[0][i] * mVectors[1][i]; 
     cout << startIndex << " " << endIndex << " " << i << endl; 

     sem_post(mSem); 
    } 
} 
+0

您對fork()的工作方式的理解完全正確。你顯示的代碼應該做你想要的。關於調試,您需要完成遊戲。嘗試在調用fork()之前打印一行。嘗試從'ProcessDotOperation'內打印參數和'getpid()'的值。嘗試在wait()調用之前打印'pID'的值。 – 2012-03-29 01:53:21

+0

'ProcessDotOperation'的代碼是什麼? – JaredPar 2012-03-29 01:53:37

+0

* Aside *:考慮使用['std :: thread'](http://en.cppreference.com/w/cpp/thread/thread)而不是'fork()'和共享內存。 – 2012-03-29 01:56:05

回答

2

有人正在第二次調用MultiProcessDot。

1

我認爲你需要的waitpid()周圍循環。正如它寫的,你等一次,沒有爲一個死去的孩子四處閒逛,如果孩子還沒有死,立即返回。當然,這允許父母繼續進行其他活動。

我不確定這是對您觀察內容的完整說明,但我們無法看到您的跟蹤代碼。打印每個消息的過程PID等。