如何在linux C ++中启动进程

时间:2012-12-08 11:45:11

标签: c++ linux process

我尝试使用exec()函数,但我需要unix / linux的函数,可以用以下函数启动进程:

  1. 工作目录
  2. Arguements
  3. 重要!环境变量,如LD_PRELOAD
  4. 谢谢!

2 个答案:

答案 0 :(得分:4)

如果你fork()你得到当前进程的副本(那么相同的工作目录),然后你可以执行你需要的参数,这将替换当前程序文本(代码)与目标可执行文件中的内容。尝试使用'man exec'或谷歌'fork exec'作为例子。

例如

if (fork() == 0) {
  // Child process
  exec("./test", "./test", "-a", NULL); // check the null though
}
// Parent process

希望有所帮助

答案 1 :(得分:0)

您可以使用execle或execvpe使用参数启动命令并覆盖环境变量(请参阅man execvpe)。例如:

#include <unistd.h>

int main(int argc, char** argv[]) {
    char * const environment[] = {"TOTO=Hello world", NULL};
    char * const args[] = {"bash", "-c", "pwd; echo ""TOTO is $TOTO""", NULL};
    chdir("/");
    execvpe("bash", args, environment);
}

输出

/
TOTO is Hello world