2012-11-30 36 views
0

我是C總共的初學者。 我有這樣一個程序,可以找到最多可以打開的進程。試圖找出我可以打開的最大進程數量是多少

我出來與此代碼:

int main() { 

while (1){ 
    pid_t pid = fork(); 
    if(pid) { 
     if (pid == -1){ 
      fprintf(stderr,"Can't fork,error %d\n",errno); 
      exit(EXIT_FAILURE); 
     }else{ 
      int status; 
      alarm(30); 
      if(waitpid(pid, &status, 0)==pid) { 
       alarm(0); 
       // the child process complete within 30 seconds 
       printf("Waiting."); 
      }else { 
       alarm(0); 
       // the child process does not complete within 30 seconds 
       printf("killed"); 
       kill(pid, SIGTERM); 
      } 
     } 
    } 
    else{ 
     alarm(30); 
     printf("child"); 
    } 
} 
} 

事情是這樣的程序導致我的筆記本電腦崩潰..: - |

我認爲當程序不能打開更多的進程時,我會從fork()得到-1,然後退出程序。那麼,它沒有發生。

有什麼想法? 我在這裏錯過了什麼?

謝謝!

+0

你是初學者,你寫了這個?你對Unix編程有多熟悉? –

回答

1

如果你真的想知道你可以打開多少個進程,你可以使用sysconf調用,尋找_SC_CHILD_MAX變量。 Check here

+0

這可能是正確的方法..但我需要實際計算它。用fork()的舊時尚方式,並最終殺死我創建的所有子進程 – Tomer

0

U不能「打開」一個過程。你可以創建他們。

_CHILD_MAX是一個常量,其中包含最大值no。可以創建的子進程的子進程。它在unistd.h標題中定義。要查詢,請使用sysconf函數。將CHILD_MAX參數傳遞給sysconf,其中SC前綴。

#define _POSIX_SOURCE 
#define _POSIC_C_SOURCE 199309L 
#include<stdio.h> 
#include<unistd.h> 

int main() 
{ 
    int res; 
    if((res==sysconf(_SC_CHILD_MAX))==-1) 
     perror("sysconf"); 
    else 
     printf("\nThe max number of processes that can be created is: ", CHILD_MAX); 

    return 0; 
} 
相關問題