C++ 如何在进程之间传递命令行参数?

问题描述 投票:0回答:3

我有一个父进程需要将命令行参数发送给其子进程?我怎样才能做到这一点?我的意思是从parent.cpp到child.cpp? 谢谢

c++ command-line process pipe args
3个回答
2
投票

#POSIX(Linux)解决方案:

使用

execvp(const char *file, char *const argv[])
运行带有参数的程序来代替当前程序。您作为引用传递的
argv[]
遵循与传入
argv[]
中的
main()
参数相同的逻辑。

如果您想保持当前进程运行并在不同的进程中启动新程序,那么您必须首先

fork()
。粗略的想法是这样的:

pid_t pid = fork();  //  creates a second process, an exact copy of the current one
if (pid==0)  {  // this is exectued in the child process
    char **argv[3]{".\child","param1", NULL }; 
    if (execvp(argv[0], argv))   // execvp() returns only if lauch failed
         cout << "Couldn't run "<<argv[0]<<endl;   
}
else {  // this is executed in the parent process 
    if (pid==-1)   //oops ! This can hapen as well :-/
         cout << "Process launch failed";  
    else cout << "I launched process "<<pid<<endl; 
}

#Windows 解决方案

最简单的 Windows 替代方案是使用 ms 特定的

_spawnvp()
或类似功能。它采用与 exec 版本相同的参数,第一个参数告诉您是否想要:

  • 替换调用进程(如posix中的exec)
  • 创建一个新进程并保留调用进程(如上面的 fork/exec 组合)
  • 或者即使您想挂起调用进程直到子进程完成。

0
投票

如果使用fork(),则子进程继承父进程。

http://man7.org/linux/man-pages/man2/fork.2.html

如果您的意思只是在内存中的对象实例之间传递变量,那么您需要为

int argc
char * argv[]
创建变量来传递。


0
投票

在父母身上。使用

system("child_application my arg list");

儿童时期。使用

int main(int argc, char *argv[])

为了轻松解析参数,请尝试 boost program_options 库。

在unix系统中可以使用

fork
。子进程获取所有父进程内存。

© www.soinside.com 2019 - 2024. All rights reserved.