2012-11-30 37 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; 
} 
相关问题