2013-05-01 334 views
-2

關於進程動態池的問題。我需要保留自由進程的信息。如果免費進程的數量少於N,我應該創建新的進程。但是,我知道free變量在每個過程中都是相同的。如何使free變量爲「全局」,並且在子進程中進行更改將會在父進程中更改變量,然後父進程可以檢查該進程並讓更多子進程進行更改?像共享內存和其他IPC一樣。一點困惑與他們。父進程和子進程的全局變量

free=5; 
for (i=0;i<5;i++) // create 5 pre-forks 
    { 
     pid=fork(); 
     if (pid==0) //child 
     { 
      break; 
     } 
     else//parent 
     { 

     } 
    } 

    while (1) 
    { 
     if (pid==0) // child 
     { 
      newsock = accept(listensock, NULL,NULL); 
      free--; //children is busy 
      send(newsock, buffer, nread, 0); 
      close(newsock); 
      free++; 
     } 
     else if (pid>0) // parent 
     { 
      if ...// if less than n fork() more 
     } 
    } 
+2

你回答了你自己的問題。你可以使用共享內存。在網上查找有關共享內存的文檔。如果你想在正在運行的實體之間共享地址空間,請使用線程。如果你使用線程,如果你使用互斥量,他們可以安全地共享共享內存。 – bspikol 2013-05-01 12:45:20

回答

0

正如您所說的,您可以使用共享內存來存儲不同進程之間共享的變量。其中一個進程必須創建該共享內存與shmget

shmget需要一個密鑰來標識共享內存區域,大小和一些其他選項。創建的常見選項是IPCCREAT | 0666以使用unix權限創建它0666

其他進程調用shmget並將0作爲使用已初始化段的最後一個參數。

處理方向空間與共享內存進行連接,你必須使用shmat

例子:

#define KEY ((key_t) 1234) //Any value, just dont overlap other applications in the machine 
#define SIZE sizeof(int) 

int* free; 

int id = shmget(KEY, SIZE, IPCCREAT | 0666); 
if (id < 0) //Error... 

free = (int*) shmat(id, 0, 0); 
if (free <= (int*)(0)) // shmat failed... 

//At this point, you can use free as a normal variable 
*free = 5; 
*free++; 
... 
//As various processes can access free, you must use any control mechanism (mutex, semaphores...) 

shmdt(id); //Unlink shared memory segment 
+0

您確實應該使用POSIX'shm_open()'來代替。使用起來更容易,不太可能發生重大沖突。 – Hasturkun 2013-05-01 13:14:50

+1

共享內存是硬變體,可以使用pipe()解決嗎? – 2013-05-01 13:20:53

+0

@NatKup管道是兩個進程之間的單向連接。你有N個具有雙向通信的進程,如果你不使用線程,共享內存就是要走的路。 – Evans 2013-05-01 13:39:29