HIN
HIN

Reputation: 21

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 1500
xdotool 1500

This is the output:

command is xdotool
argument is mousemove
x is 1500
y is 1500

mousemove: Unknown command: 1500
Run 'mousemove help' if you want a command list

Upvotes: 1

Views: 960

Answers (1)

countunique
countunique

Reputation: 4296

When assembling args, you need to add "xdotool" as the first argument.

From man page for 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};.

Upvotes: 0

Related Questions