C语言 尝试找出我可以打开的进程的最大数量

mnemlml8  于 2023-10-16  发布在  其他
关注(0)|答案(2)|浏览(133)

我是一个C语言的初学者。我有这个assginment来验证一个程序,将找到我可以打开的进程的最大数量。
我得到了这个代码:

  1. int main() {
  2. while (1){
  3. pid_t pid = fork();
  4. if(pid) {
  5. if ( pid == -1){
  6. fprintf(stderr,"Can't fork,error %d\n",errno);
  7. exit(EXIT_FAILURE);
  8. }else{
  9. int status;
  10. alarm(30);
  11. if(waitpid(pid, &status, 0)==pid) {
  12. alarm(0);
  13. // the child process complete within 30 seconds
  14. printf("Waiting.");
  15. }else {
  16. alarm(0);
  17. // the child process does not complete within 30 seconds
  18. printf("killed");
  19. kill(pid, SIGTERM);
  20. }
  21. }
  22. }
  23. else{
  24. alarm(30);
  25. printf("child");
  26. }
  27. }
  28. }

问题是这个程序导致我的笔记本电脑崩溃..:-|
我假设当程序无法打开更多进程时,我将从fork()获得-1,然后退出程序。好吧,它没有发生。
知道吗,我错过了什么
谢谢你,谢谢

gkn4icbw

gkn4icbw1#

如果你真的想知道你可以打开多少个进程,你可以使用sysconf调用,查找_SC_CHILD_MAX变量。Check here

30byixjq

30byixjq2#

你不能“打开”一个进程。你可以“创造”他们。

CHILD_MAX是一个常量,包含可以创建的子进程的最大数量。在 unistd.h header中定义。要查询,请使用sysconf函数。将CHILD_MAX参数传递给前缀为_SC_sysconf

  1. #include <stdio.h>
  2. #include <unistd.h>
  3. int main(){
  4. int res = sysconf(_SC_CHILD_MAX);
  5. if (res == -1) {
  6. perror("sysconf");
  7. } else {
  8. printf("The max number of processes that can be created is: %d\n", res);
  9. }
  10. return 0;
  11. }

相关问题