Is it safe to fork() within a callback function in C?

115 views Asked by At

I'm outlining a program.

Basically, I want to use nftw to traverse the directory tree and perform a task(myexecutable).

this function nftw takes for example (fn) as an argument and uses it as a callback function.

Now I am planning to use a classic fork-exec inside this callback function that I have defined to gain as much speed as possible by distributing the task over multiple instances of the same process for different files to make that happen almost at simultaneously.

lets say I want to do action P on every file. so I define my callback function like:

static int fn(const char* pathname, const struct stat* st, int tf, struct FTW* ff){
    if(tf == FTW_F){
        if(fork() == 0){
            execl("myexecutable", "myexecutable", pathname, NULL);
            exit(0);
        }else{
            return 0;
        }
    }
}

also different instances of myexecutable do not in anyway depend on each other or share any resources. and they don't need to communicate with the parent process and vice versa.

can this cause a problem with the calling function?

should I expect nftw to go crazy over this or show undefined behavior?

1

There are 1 answers

0
dbush On

This won't be a problem because you're calling execl immediately after the new process is forked. All process memory, including any state nftw might have, is replaced with that of the new program.

The only change you should make is to call _exit instead of exit in case execl fails. That way it won't call any atexit handlers and potentially cause issues with open file descriptors in the parent process.