在父进程中,您想要
fork.
Fork创建一个全新的进程,并将子进程的pid返回给调用进程,将0返回给新的子进程.
在子进程中,您可以使用类似execl的内容来执行所需的辅助程序.
在父进程中,您可以使用waitpid等待子进程完成.
这是一个简单的说明性示例:
#include
#include
#include
#include
#include
int main()
{
std::string cmd = "/bin/ls"; // secondary program you want to run
pid_t pid = fork(); // create child process
int status;
switch (pid)
{
case -1: // error
perror("fork");
exit(1);
case 0: // child process
execl(cmd.c_str(), 0, 0); // run the command
perror("execl"); // execl doesn't return unless there is a problem
exit(1);
default: // parent process, pid now contains the child pid
while (-1 == waitpid(pid, &status, 0)); // wait for child to complete
if (!WIFEXITED(status) || WEXITSTATUS(status) != 0)
{
// handle error
std::cerr << "process " << cmd << " (pid=" << pid << ") failed" << std::endl;
}
break;
}
return 0;
}