Skip to content
Advertisement

Count maximum amout of parent processes in Linux

#include <sys/types.h>
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/resource.h>
#include <errno.h>
int main()
{
  int pid;
  int temp = 0;
  while(1){
  pid = fork();
  if(pid == 0)
     return 0;
   if(pid == -1){
      if (errno == EAGAIN)
      printf("%d n limit process", (int)temp);
  exit(-1);}
  temp++;
  }
       return 0;
}

Here is my code. But teacher said it’s incorrect and something is wrong in if (pid == 0) condition body. Help me out please. Thank you!

Advertisement

Answer

fork() returns 0 for child process, >0 for parent process, and a negative value if there were errors.

Your child process finishes immediately, so actually you never manage to spawn multiple processes at the same time, as they are forked and finish.

What you want to do is to keep the child process running, until the parent tells it to shut down (for example via signal).

if (0 == pid) {
    // I am child process -> wait until signal
    // for example: sleep(MAX_INT);
}

and in parent process you need to shutdown all child processes when the test finishes. For example you could put all of child processes into one process group and send a signal to it:

  if (pid == -1) {
    if (errno == EAGAIN) {
      // print output
      printf("%d n limit process", temp);
      // kill all child processes (you 
      kill(0, SIG_TERM); // you might need to set up signal handler in parent process too - see 'signal')
      // wait for child processes to finish and cleanup (we know there is 'temp' count of them);
      for (int = 0; i < temp; ++i) {
        wait(NULL);
      }
    }
  }

Refs:

http://man7.org/linux/man-pages/man2/kill.2.html

http://man7.org/linux/man-pages/man2/waitpid.2.html

http://man7.org/linux/man-pages/man2/signal.2.html

Advertisement