Home > Net >  failing to execute a shell command in windows using WindowsAPI
failing to execute a shell command in windows using WindowsAPI

Time:12-22

I am trying to execute a ping command in windows via their ShellExecute function.

ShellExecute(0, L"open", L"cmd.exe", normToWide(command).c_str(), 0, SW_HIDE);

This is how i call the Function. to get the wide string i use this function

std::wstring normToWide(std::string str)
{
    std::wstring str2(str.length(), L' ');
    std::copy(str.begin(), str.end(), str2.begin());
    return str2;
}

the command is this:

ping 127.9 -l 4 -n 300 > output.txt

Although the ip is invalid it should not matter as output.txt should still be populated with some sort of error message at hte least. What is going on with my function?

I expected there to be a output.txt file with the output of the command I also tried hardcoding my command to make sure it was not a widestr issue

CodePudding user response:

The problem is ping is not a built in command in cmd.exe and it will not automatically execute the command you pass to it, thus ping even if it is installed and in the command path will not be executed. To fix this you have two choices.

The first is to prefix the command string with the /C option which "Carries out the command specified by string and then terminates" like so

/C ping 127.9 -l 4 -n 300 > output.txt

This will force cmd.exe to execute ping if it is in installed and in the command path.

The second is just as easy - just specify ping.exe as the command for ShellExecute to execute instead of cmd.exe.

ShellExecute(0, L"open", L"ping.exe", normToWide(command).c_str(), 0, SW_HIDE);

CodePudding user response:

If you want to execute ping.exe and capture the output it produces, it'll be much cleaner to use something on this order:

FILE *f = _popen("ping 127.9 -l 4 -n 300"); 
char buffer[256]; 

while (fgets(buffer, sizeof(buffer), f) { 
    // `buffer` contains a line of output from `ping`
}

CodePudding user response:

ShellExecute(NULL,NULL,L"cmd.exe", L"/K ping 127.9 -l 4 -n 300 > d://test.txt",NULL, SW_SHOWNORMAL);

/k: end cmd window does not disappear /c: end cmd window disappear

  • Related