I am working on a multithreaded process that forks to execute another process. Sometimes, the fork may error if the execution file does not exist. Since this process has multiple threads running prior to fork I have a couple questions:
- Are threads copied over to the forked process.
-
What is the best practice to handling an error from fork with a multithreaded process. For example:
/* in a multithreaded process */ pid = fork(); if(pid == 0) { execlp(filename, filename, NULL); fprintf(stderr, "filename doesn't exist"); /* what do i do here if there's multiple threads running from the fork? */ exit(-1); }
Well, the
forkdoesn’t error if the executable file doesn’t exist. Theexecerrors in that case. But, to your actual question, POSIX states thatforkcreates a new process with a single thread, a copy of the thread that calledfork. See here for details:So what you have is okay, if a little sparse 🙂
A single thread will be running in the child and, if you cannot
execanother program, log a message and exit.And, in the rationale section, it explains why it was done that way: