Operating System - HP-UX
1833006 Members
3293 Online
110048 Solutions
New Discussion

How to execute a child process by a function call on UNIX systems?

 
emender
Occasional Contributor

How to execute a child process by a function call on UNIX systems?

Dear all:
In C language,while I define several function pointers in a program by a function array, is there any function call which is capable of optionally executing those functions?

funca(){}
funcb(){}
funcc(){}
............
void (*func[])(int)={funca,funcb,funcc.......}

void main(int argc,char *argv[])
{
............

execute(func[argc],....);

..............
}

Does the "execute" function exist in UNIX C language?
"execute" is just an example.

Best Regards!!!
dentice
3 REPLIES 3
Wodisch
Honored Contributor

Re: How to execute a child process by a function call on UNIX systems?

Hi,

you are already pretty close, it's the "exec*" family of system calls. See "man 2 exec" to get the details. There you will find the hint that the system call to actually start a new process is called "fork" (see "man 2 fork"). The exit code of that system call is zero for the new process, the new process's PID for the parent, or negative if you encountered an error.
So your code will look like:

result = fork();
if (result > 0) {
printf "now going for that function");
func[arg]();
}
else if (result < 0) {
perror ("fork() did not work!");
} else {
printf ("I am the old process, now called "parent");
}

FWIW,
Wodisch
Mike Stroyan
Honored Contributor

Re: How to execute a child process by a function call on UNIX systems?

I think wodisch answered the subject line, but not the real question. You only use fork and exec to start a new process from a new program file.
Your actual question seems to be about just calling a function from a function pointer. In that case you would use-
(*func[i])(arg);
to call the function. You don't need another process or any extra function call to use a function pointer. (The compiler might insert a call to one of the dyncall functions to handle function pointers to shared library code.)
doug hosking
Esteemed Contributor

Re: How to execute a child process by a function call on UNIX systems?

Mike's answer seems to be what you want.
It sounds like you just want to do an indirect
function call, not create a new process to do
so.

If for some reason you really do want to
use the fork() approach mentioned above, be
sure to also learn about the wait() family
of calls. Otherwise, you could have problems
with insufficient cleanup from terminated
child processes, especially if you create
many of them.