简体   繁体   English

在 linux 上的 C++ 中执行 shell 命令 xdotool

[英]Execute shell command xdotool in C++ on linux

#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);
    */
}

What is wrong with this code?这段代码有什么问题?
The command runs, but seems to interpret every argument as another execution.该命令运行,但似乎将每个参数解释为另一个执行。
Not sure, but I believe it is running:不确定,但我相信它正在运行:

xdotool mousemove xdotool mousemove
xdotool 1500 xdotool 1500
xdotool 1500 xdotool 1500

This is the output:这是 output:

command is xdotool命令是 xdotool
argument is mousemove参数是鼠标移动
x is 1500 x 是 1500
y is 1500 y 是 1500

mousemove: Unknown command: 1500 mousemove:未知命令:1500
Run 'mousemove help' if you want a command list如果需要命令列表,请运行“mousemove help”

When assembling args , you need to add "xdotool" as the first argument.组装args时,您需要添加“xdotool”作为第一个参数。

From man page for execvp :execvp手册页

The first argument, by convention, should point to the filename associated with the file being executed.按照惯例,第一个参数应该指向与正在执行的文件关联的文件名。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM