我有一个父进程需要将命令行参数发送给其子进程?我怎样才能做到这一点?我的意思是从parent.cpp到child.cpp? 谢谢
#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 解决方案
_spawnvp()
或类似功能。它采用与 exec 版本相同的参数,第一个参数告诉您是否想要:
如果使用fork(),则子进程继承父进程。
http://man7.org/linux/man-pages/man2/fork.2.html
如果您的意思只是在内存中的对象实例之间传递变量,那么您需要为
int argc
和 char * argv[]
创建变量来传递。
在父母身上。使用
system("child_application my arg list");
儿童时期。使用
int main(int argc, char *argv[])
为了轻松解析参数,请尝试 boost program_options 库。
在unix系统中可以使用
fork
。子进程获取所有父进程内存。