1
$\begingroup$

I am curious as to the overhead cost of spawning child processes using fork in a Linux environment. Suppose I have a C program such as

void run_computation(int x);

int main() {
    for (int k=0; k<10; k++) {
        if ( fork() == 0 ) {
            run_computation(k);
            break;
        }
    }

    return 0;
}

Assuming that no global state is modified by run_computation, how efficient in terms of overhead is the setting up of the child processes?

To help understand where I'm coming from, I'd like to write my own regex engine (for self-learning) and am imagining using fork to implement the NFA. So, am I incurring an unreasonable cost in such an implementation compared to other methods?

$\endgroup$
2
$\begingroup$

The (non-negligible) cost is the set up of the in-kernel structures to keep track of the new process (setting up page tables and so on).

You can easily measure it: Write a small program just like the one you have:

#include <unistd.h>

/* Define FORK for forking version */

#ifdef FORK
#define ROUNDS 10000
#else
#define ROUNDS 10000000
#endif

int main(void)
{
        for(int i = 0; i < ROUNDS; i++) {
#ifdef FORK             
                if(fork() == 0) /* Child */
                        return 0;
#endif          
        }
}

and run it under time(1). Here I get (Intel(R) Core(TM) m5-6Y57 CPU @ 1.10GHz, Fedora 32, kernel 5.7.15-200.fc32.x86_64, gcc-10.2.1-1.fc32, no optimization; just checked that the non-forking code does it's rounds) for non-forking:

real    0m0.027s
user    0m0.024s
sys     0m0.004s

For forking:

real    0m0.436s
user    0m0.016s
sys     0m0.414s

Very definitely not advisable.

$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.