tags:

views:

342

answers:

3

I have a C++ function that I'd like to call using execvp(), due to the way my program is organized.

Is this possible?

+2  A: 

excecvp() is meant ot start a program not a function. So you'll have to wrap that function into a compiled executable file and then have that file's main call your function.

Brian R. Bondy
+5  A: 

All of the exec variants including execvp() can only call complete programs visible in the filesystem. The good news is that if you want to call a function in your already loaded program, all you need is fork(). It will look something like this pseudo-code:

int pid = fork();
if (pid == 0) {
    // Call your function here. This is a new process and any
    // changes you make will not be reflected back into the parent
    // variables. Be careful with files and shared resources like
    // database connections.
    _exit(0);
}
else if (pid == -1) {
    // An error happened and the fork() failed. This is a very rare
    // error, but you must handle it.
}
else {
    // Wait for the child to finish. You can use a signal handler
    // to catch it later if the child will take a long time.
    waitpid(pid, ...);
}
Ken Fox
A: 

Creating processes can be heavyweight. If you really only want to call your function in parallel why not using threads. There are many platform independent libraries available that have threading support for C++ like Boost, QT or ACE.

If you really need your function to be executed in another process you can use fork or vfork. vfork may not be available on every platform and it has it's drawbacks so make sure if you can use it. If not just use fork.

lothar