gpt4 book ai didi

c++ - 如何在 Linux 中使用 exec 函数族执行 a.out 文件

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:13:10 25 4
gpt4 key购买 nike

这个c++程序的目的是理解操作系统中的并发进程机制。下面的代码是针对一个进程的子函数。子进程有他们的编号,NO.5 和 NO.6。

我正在尝试在 NO.6 进程中执行 a.out 文件。我正在尝试这样做。

void ChildFunction_For_ProcessNO.4(int i){
switch(i){
case(5):
cout << "This is process five, and the ID for this process is " << getpid() << '\n'
<< "and the ID for the parent process is " << getppid() << '\n';
CreateThreads_Five();
cout << "Process five has ended.\n" << '\n';
break;
case(6):
cout << "This is process six, and the ID for this process is " << getpid() << '\n'
<< "and the ID for the parent process is " << getppid() << '\n';
execl("./a.out", "a.out", NULL);
//and I also tried this way
execl("Home/CLionProjects/Project_1/a.out", "a.out", NULL);
char buf[100];
cout << "getcwd: " << getcwd(buf, sizeof(buf))) << endl;
cout << "Process six has ended.\n";
break;
}

getcwd 的输出是这样的

getcwd: /home/chengxuyuan/CLionProjects/Project_1/cmake-build-debug

a.out文件已经和c++程序一起放在文件夹中了。 the screenshot of the working directory编译进行得很顺利,但是 a.out 文件中没有应该是 Hello world 的输出。我怎么解决这个问题。非常感谢!

最佳答案

getcwd 输出显示您必须将文件 a.out 放入

/home/chengxuyuan/CLionProjects/Project_1/cmake-build-debug

你的尝试

execl("Home/CLionProjects/Project_1/a.out", "a.out", NULL);

错误,这不是完整路径。你将不得不使用

execl("/home/chengxuyuan/CLionProjects/Project_1/a.out", "a.out", NULL);

顺便说一句:您应该指定与要运行的程序使用的参数 0 相同的值,即

execl("/home/chengxuyuan/CLionProjects/Project_1/a.out", "/home/chengxuyuan/CLionProjects/Project_1/a.out", NULL);

execl("./a.out", "./a.out", NULL);

这是 shell 会做的,也是大多数程序所期望的。

关于c++ - 如何在 Linux 中使用 exec 函数族执行 a.out 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58411950/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com