
Unix: Need help with fork() or other methods of multithreading
[I hope this isn't a duplicate again. Dang Netscape!]
Fri, 16 Jul 1999 17:38:38 GMT,
Quote:
> SNIP
> > system(). The only problem is that these appear to, upon successful
> execution
> > of the shell script, exit (rather than return to the c script). I did
> a man on
> > system and execve and noticed that they both spawn their own child
> processes,
> > but never return to the caller.
> > Is there some way to fork() and then execute the script in a child
> process so
> > that my c script can tell the user that it successfully started the
> script?
> > And how does one go about using the process ID that fork() returns to
> actually
> > do anything useful? The man documentation on this appears to be
> somewhat
> > skimpy...
C programs aren't normally called "scripts".
Quote:
> system() will return after completion.
More precisely system() (if implemented at all, and successful)
must wait for the specified program to complete, then return;
in Unix this will almost certainly be done by fork()ing a child
and having the child exec* the desired script (or program)
while the parent waits for it.
Quote:
> this should work too:
> if(!fork())
> {
> system("./world_domination");
> exit(0);
> }
> else
> {
> printf("Process started\n");
> }
No, here the child will wait for the grandchild --
and lose any error status system() managed to keep --
but the parent doesn't wait for the child.
The idiom is:
#if UNIX_SPECIFIC /* and very incomplete */
pid = fork();
if( pid == -1 ) { /* handle error */ }
/*else*/ if( pid == 0 ) /* child*/
{
execv("pgm",args); /* or other exec* variant */
/* error handling for exec failure */
exit(some_error); /* clean up extra child */
}
else /* parent */
{
printf("Started %d\n", (int)pid);
/* or other computation and/or reporting */
err = wait(pid); /* or wait3() until pid occurs */
printf("Completed %d\n", (int)pid);
/* or other reporting, including err */
}
#endif
The child pid can also be used to kill() it, in
some system-specific ways to check it's status,
and to build almost-guaranteed-unique filenames,
among other things.
This is all OFFTOPIC for comp.lang.c and belongs in
something more like comp.unix.programmer. Or get
any textbook or reference on Unix programming;
Stevens is the classic (but mine is not to hand)
and there must be at least one O'Reilly applicable.
- david.thompson at but not for trintech.com