Detecting exec(2) failing after performing fork(2)?

Stig Jacobsen shj at login.dkuug.dk
Fri Mar 1 13:19:26 AEST 1991


When my application desires to spawn off a background process,
I use something roughly like this:

int spawn(char *path, ...)
{

   if (fork() == 0)
      execlp(path, NULL);

}

This is fine if the exec..() call goes well. However, if the exec()
call fails, the error is not reported back to the parent. I get
a SIGCLD of course, but what I'd really like is that my spawn()
function just returns an error, if the exec() call fails. So far
the best solution that I've come up with is,

int spawn(char *path, ...)
{

   if (access(path, R_OK|X_OK) != 0)
      return -1;
   if (fork() == 0)
      execlp(path, NULL);

}

But this is not an elegant solution, nor is it entirely safe:
If someone unlinks 'path' between the access() and the exec()
call (not _that_ unlikely if the system is heavily loaded),
I won't detect the error anyways!

So - what does everybody else do? Am I overseeing something
totally obvious?

--
Stig Jacobsen
shj at login.dkuug.dk / sysadm



More information about the Comp.unix.programmer mailing list