【问题标题】:Execute shell command xdotool in C++ on linux在 Linux 上用 C++ 执行 shell 命令 xdotool
【发布时间】:2020-07-31 12:40:01
【问题描述】:
#include <unistd.h>
#include <cstdio>
#include <iostream>
#include <string.h>

using namespace std;

int main(void)
{

//  Trying to execute:
//      xdotool mousemove 1500 1500

//    char command[] = "/usr/bin/xdotool\0";
    char command[] = "xdotool\0";
    char argument[] = "mousemove\0";
    int src_x = 1500;
    int src_y = 1500;

    char x[5];
    memset(x, 0x00, 5);
    sprintf(x, "%d", src_x);
    char y[5];
    memset(y, 0x00, 5);
    sprintf(y, "%d", src_y);

    cout << "command is " << command << "\n";
    cout << "argument is " << argument << "\n";
    cout << "x is " << x << "\n";
    cout << "y is " << y << "\n\n";

    char *args[] = {argument, x, y, nullptr};
    return execvp(command, args);
/*    char *args[] = {x, y, nullptr};
    char *com[] = {argument, nullptr};
    return execvpe(command, com, args);
    */
}

这段代码有什么问题?
该命令运行,但似乎将每个参数解释为另一个执行。
不确定,但我相信它正在运行:

xdotool 鼠标移动
xdotool 1500
xdotool 1500

这是输出:

命令是 xdotool
参数是鼠标移动
x 是 1500
y 是 1500

mousemove:未知命令:1500
如果需要命令列表,请运行“鼠标移动帮助”

【问题讨论】:

    标签: c++ linux exec xdotool


    【解决方案1】:

    在组装args时,需要添加“xdotool”作为第一个参数。

    来自man pageexecvp

    按照惯例,第一个参数应该指向文件名 与正在执行的文件相关联。

    所以应该是char *args[] = {"xdotool", argument, x, y, nullptr};

    【讨论】: