由于我的程序组织方式,我有一个C ++函数,我想用execvp()调用它。
这可能吗?
答案 0 :(得分:5)
所有exec变体(包括execvp())只能调用文件系统中可见的完整程序。好消息是,如果你想在已经加载的程序中调用一个函数,你只需要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, ...); }
答案 1 :(得分:2)
excecvp()意味着启动一个程序而不是一个函数。因此,您必须将该函数包装到已编译的可执行文件中,然后让该文件的主函数调用您的函数。
答案 2 :(得分:0)