MOHAMED
MOHAMED

Reputation: 43558

What could be the risk of executing fork many times?

I have a program that execute fork many time sequentially (and not at the same time).

What could be the risk of a such behaviour.

Because some times I get a fork error after execution fork many times

Upvotes: 2

Views: 1523

Answers (2)

slim
slim

Reputation: 41263

If you have your own UNIX/Linux system, I suggest trying it.

Compile the C program:

int main(int argc, char *argv[]) {
    while(true) {
        int rc = fork();
        if(rc == -1) {
            perror("fork failed");
        }
    }
}

Run it as a normal user. See what happens.

Run it as root. Watch your system grind to a halt. You'll probably want to reboot to recover.

fork() is a system call, and your code should always check for errors from system calls, so you should have the information on why it failed. That goes for other system calls such as malloc() or fopen() too.

Upvotes: 1

musicinmybrain
musicinmybrain

Reputation: 641

The Open Group Base Specifications Issue 7, IEEE Std 1003.1, 2013 Edition, describes what might be happening pretty clearly:

The fork() function shall fail if:

[EAGAIN] The system lacked the necessary resources to create another process, or the system-imposed limit on the total number of processes under execution system-wide or by a single user {CHILD_MAX} would be exceeded.

The fork() function may fail if:

[ENOMEM] Insufficient storage space is available.

You might protest that your child processes are not long-running and there should not be too many active at once. In this case, the problem is probably that your parent process is leaving “zombie processes”—those that have terminated but still occupy slots in the process table—by failing to call wait to clean up after its children. You might call wait synchronously, in the sense that the parent process has nothing better to do than wait for the child process to execute and terminate, or you might call wait in response to a SIGCHLD signal. Pleasantly, wait and waitpid are async-signal-safe, so you can safely call them from a signal handler and leave the main flow of your program unaffected.

Upvotes: 3

Related Questions