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

标签 c++ function exec

由于我的程序的组织方式,我想使用 execvp() 调用一个 C++ 函数。

这可能吗?

最佳答案

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

关于c++ - 我可以在程序中定义的函数上使用 execvp() 吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/648917/

相关文章:

c - 在 C 中对字符数组使用 qsort

c - C 中的 execvp 不通过 ar

c++ - OpenGL 第三人称相机

c++ - unordered_set::erase(pos) 是否保留元素的顺序?

c++ - 从数组中删除对象

c++ - 可变参数函数——我什么时候应该使用 &&... 与 &...?

C++ 删除或覆盖文件中的现有信息

javascript - 了解 Javascript .sort 参数

c - 分解shell脚本;引擎盖下会发生什么?

java - Runtime.exec 失败,没有任何异常/警告/错误代码