Detecting exec(2) failing after performing fork(2)?
mike at bria
mike at bria
Sat Mar 2 08:20:29 AEST 1991
In an article, login.dkuug.dk!shj (Stig Jacobsen) writes:
|When my application desires to spawn off a background process,
|I use something roughly like this:
[ example deleted ]
|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?
Some time ago, I wrote a spawn function (but then I got religion, and
only use fork/exec explicitly :-)
The only caveat is if the spawned program returns an exit status of 255,
it will look like the spawn failed (this was never a big issue for me,
so I left it). Here goes:
#include <stdio.h>
main(argc,argv)
int argc;
char *argv[];
{
printf("spawn returned %d\n",spawn(argv[1],&argv[1]));
return(0);
}
spawn(path,argv)
char *path, *argv[];
{
int ret, xit;
if ( (ret = fork()) > 0 ) {
if ( wait(&xit) == -1 )
return(-1);
}
else if ( ret == 0 ) {
if ( execvp(path,argv) == -1 )
exit(-1);
}
else
return(-1);
return(xit >> 8);
}
--
Michael Stefanik, MGI Inc., Los Angeles| Opinions stated are not even my own.
Title of the week: Systems Engineer | UUCP: ...!uunet!bria!mike
-------------------------------------------------------------------------------
Remember folks: If you can't flame MS-DOS, then what _can_ you flame?
More information about the Comp.unix.programmer
mailing list