2013-03-24 59 views
0

我試圖讓2個進程同時在一個任務上啓動(例如對一個數進行計數)。我爲每個進程設置了2個就緒標誌,並執行一個while循環來檢查兩個標誌是否都啓動。然後這2個進程將在檢查通過後開始計數。這裏是不工作的代碼,我不知道爲什麼:正在同步2個進程

int p1ready=0; 
int p2ready=0; 
int onebil = 1000000000; 

int main(){ 

int pid; 
int exit_code; 

pid=fork(); 
if(pid==0){ 
//child1 
    int count1=0; 
    p1ready=1; //signal 
    while(!(p1ready&p2ready))'//wait until 2 processes are both ready 

    while(count1!=onebil){ 
     count1++; 
    } 
    exit(0); 
} 
else{ 
    pid=fork(); 
    if(pid==0){ 
    //child2 
     int count2=0; 
     p2ready=1; //signal 
     while(!(p1ready&p2ready));//wait until 2 processes are both ready 
     while(count2!=onebil){ 
      count2++; 
      } 
     exit(0); 
    } 
    else{ 
    //parent 
     //do stuff 
    } 
return 0; 
} 

這段代碼的問題是,在child1和的child2,只有自己準備標誌被設置爲1。他們看不到的旗幟其他孩子正在設置。例如,child1只看到p1ready = 1,但p2ready始終爲0.爲什麼這樣呢?我怎樣才能解決這個問題?

在此先感謝!

回答

2

您試圖同步您的流程的方式並不奏效,因爲您正在創建的每個流程都有自己的p1readyp2ready副本。

你似乎在尋找的是某種進程間通信。您可能想看看http://en.wikipedia.org/wiki/Inter-process_communication以查看可能的選項列表。

在一個簡單的情況下,像你的問題最有可能派出了你的孩子提到的進程從父進程的信號就足夠了,所以我建議你最好先看看那個。

2

當你做一個fork()時,每個進程都會獲得一個私有的新地址空間。家長和孩子不會共享任何數據。這就是進程間通信機制進入的地方。

您可能會使用信號量。看到這個鏈接:

semaphore equivalent for processes?

http://www.csc.villanova.edu/~mdamian/threads/posixsem.html

你可以準備在母公司信號燈,讓每個孩子在其上等待每個叉後,再在父釋放他們。這兩個子進程都將被釋放並在同一時間繼續執行。當然,首先執行哪個執行程序取決於OS執行調度程序。

#include <stdio.h> 
    #include <semaphore.h> 
    #include <unistd.h> 

    int p1ready=0; 
    int p2ready=0; 
    int onebil = 1000000000; 

    int main(){ 

    int pid; 
    int exit_code; 

    // create a semaphore for each child: value=0 
    sem_t *sem1 = sem_open("test_semaphore", O_CREAT|O_EXCL); 
    sem_t *sem2 = sem_open("test_semaphore", O_CREAT|O_EXCL); 

    pid=fork(); 
    if(pid==0){ 
     //child1 
     // wait on semaphore => blocks if value <= 0 
     sem_wait(sem1); 
     int count1=0; 
     // do work => a function might be better 
     while(count1!=onebil){ 
      count1++; 
     } 
     exit(0); 
    } 
    else{ 
     pid=fork(); 
     if(pid==0){ 
      //child2 
      // wait on semaphore => blocks if value <= 0 
      sem_wait(sem2); 
      // do work 
      int count2=0; 
      while(count2!=onebil){ 
       count2++; 
       } 
      exit(0); 
     } 
     else{ 
      //parent 
      // signal semaphore1 (increment) releasing child 1 
      sem_post(sem1); 
      // signal semaphore2 (increment) releasing child 2 
      sem_post(sem2); 

      // do work 

      // wait for child1/child2 
      int status; 
      wait(&status); // a child has exited 
      // do something with status 
      wait(&status); // another child has exited 
      // do something with status 

     } 
    return 0; 
    }