Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing arguments to executable not working in C++

This is the source code for "sleeper.exe" I have:

int main(int argc, char** argv) {
    cout<<argv[1];
    return 0;
}

When I call from command line like this:

C:\sleeper 5

I see

5

in command line so this works fine..

Now I am trying to call this exe from some other exe like this:

std::cout << "ret is:" << ret;
std::cout << "\n";

CreateProcess("sleeper.exe", // No module name (use command line)
               ret, // Command line
               NULL, // Process handle not inheritable
               NULL, // Thread handle not inheritable
               FALSE, // Set handle inheritance to FALSE
               0, // No creation flags
               NULL, // Use parent's environment block
               NULL, // Use parent's starting directory 
               &si, // Pointer to STARTUPINFO structure
               &pi // Pointer to PROCESS_INFORMATION structure
             )

Here ret is 5 as well and I am sure because I see it in the commandline fine:

ret is: 5

There is a file called config.mpap in the same directory and I read the value from here like this:

std::ifstream myReadFile;
myReadFile.open("config.mpap");

char output[400];
if (myReadFile.is_open()) {
    while (!myReadFile.eof()) {
        myReadFile >> output;
    }
}
myReadFile.close();

char y = output[37];
int numberOfSleeps = y - '0'; // So now numberOfSleeps is 5

And then I convert numberOfSleeps to ret like this:

char* ret = NULL;
int numChars = 0;
bool isNegative = false;
// Count how much space we will need for the string
int temp = sleepTime;
do {
    numChars++;
    temp /= 10;
} while (temp);
ret = new char[ numChars + 1 ];
ret[numChars] = 0;
if (isNegative) ret[0] = '-';
int i = numChars - 1;
do {
    ret[i--] = sleepTime % 10 + '0';
    sleepTime /= 10;
} while (sleepTime);

Can please someone help me why ret is not passed to sleeper.exe from createprocess.exe?

EDIT:

It works like this:

if (!CreateProcess(NULL, // No module name (use command line)
                   "sleeper 5", // Command line

However this does not even compile:

std::string sleeper("sleeper ");
sleeper += ret;
if (!CreateProcess(NULL, // No module name (use command line)
                   sleeper, // Command line
like image 555
Koray Tugay Avatar asked Oct 20 '22 20:10

Koray Tugay


1 Answers

The command line (second parameter of CreateProcess) takes the full command line, including the executable name. If the first argument is not NULL, it is used as the executable to run, but the command line still has to include an executable name. In the past even prepending a single space (giving an empty executable name) worked for me.

like image 191
Philipp Avatar answered Oct 23 '22 18:10

Philipp