How / Why fork () Failure

I am currently studying the fork () function in C. I understand what it does (I think). My question is why are we checking it in the next program?

#include <stdio.h> #include <unistd.h> #include <stdlib.h> int main() { int pid; pid=fork(); if(pid<0)/* why is this here? */ { fprintf(stderr, "Fork failed"); exit(-1); } else if (pid == 0) { printf("Printed from the child process\n"); } else { printf("Printed from the parent process\n"); wait(pid); } } 

In this program, we check if PID <0 is returned, which indicates a failure. Why does fork () not work?

+7
source share
4 answers

On the man page:

  Fork() will fail and no child process will be created if: [EAGAIN] The system-imposed limit on the total number of pro- cesses under execution would be exceeded. This limit is configuration-dependent. [EAGAIN] The system-imposed limit MAXUPRC (<sys/param.h>) on the total number of processes under execution by a single user would be exceeded. [ENOMEM] There is insufficient swap space for the new process. 

(This is from the OS X man page, but the reasons for other systems are similar.)

+15
source

fork can fail because you live in the real world, and not some infinitely recursive mathematical fantasy-earth, and therefore resources are limited. Specifically, sizeof(pid_t) course, and this puts a tight upper bound of 256 ^ sizeof (pid_t) on the number of times fork can possibly be successful (without any terminating processes). In addition, you also have other resources to worry about how memory is.

+8
source

Not enough memory to create a new process.

+1
source

If the kernel does not allocate memory, for example, it is very bad and will result in a fork() error.

Check out the error codes here:

http://linux.die.net/man/2/fork

+1
source

Source: https://habr.com/ru/post/958115/


All Articles