我可以在我的程序中定义的函数上使用execvp()吗?

sam*_*moz 0 c++ function exec

由于我的程序组织方式,我有一个C++函数,我想用execvp()来调用它.

这可能吗?

Ken*_*Fox 5

包括execvp()在内的所有exec变体只能调用文件系统中可见的完整程序.好消息是,如果你想在已经加载的程序中调用一个函数,你只需要fork().它看起来像这个伪代码:

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, ...);
}