fork() 和 execl() 调用后无法识别 C++ 命令 (Linux)

C++ Command not recognized after fork() and execl() call (Linux)

我正在尝试创建一个可以打开终端浏览器并浏览网站的程序。在调用子进程之前,它工作正常。出现以下错误

"xdotool: Unknown command: search --onlyvisible --name Terminal windowactivate keydown Down"

我已经在单独的终端中测试了该命令,它确实有效,但在我的代码中未被识别。我觉得这可能与 execl 没有 return 回到 main 的事实有关,但我是编程新手,所以我不确定。

这是代码

#include <iostream>
#include <string>
#include <unistd.h>

using namespace std;

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

string thread;
cout << "website: ";
cin >> thread;

const char* xdo = "xdotool";
pid_t pid = fork();
string strThread = "" + thread;
string xdoCMD = " search --onlyvisible --name Terminal windowactivate keydown Down";

if (pid < 0) {
cout << "Process failed" << endl;
return 1;
} 
else if (pid == 0) {
execl("/usr/bin/xdotool", "xdotool", xdoCMD.c_str(), (char *) NULL);
}

else {
//  sleep(1);
execl("/usr/bin/elinks", "elinks", strThread.c_str(), (char *) NULL);
}
} 

execl(3) is calling execve(2)(其参数进入已执行程序的 main)。他们 return 只在失败时才发生。

所以

execl("/usr/bin/xdotool", "xdotool", xdoCMD.c_str(), (char *) NULL);

正在调用带有两个参数的 xdotool 程序,xdotoolxdoCMD.c_str() - 作为 单个 第二个参数。

您应该将 xdoCMD.c_str() 分成几部分。从中构建一个适当的(NULL 终止!)char* 数组,然后调用 execvp(3)

实际上,您应该模仿 shell 的作用。也许你甚至可能想要 globbing (but you need to decide what kind of expansions you want; beware perhaps of code injection). See glob(7).

不要忘记检查失败(forkexecvp 等...)

顺便说一句,gdb debugger (don't forget to compile with g++ -Wall -g) and strace(1) 都有助于找到这样的错误。