I have to execute command and return the result like cmd.
I just found out the only method for this requirement.I used popen function to execute command and return the result,and then used pclose() function to close the stream and process.
But if commands are never end,for example “ping 8.8.8.8 –t” ,I can’t close process by using pclose() function.
If I kill the child process created by popen() by task manager,the pclose function works OK.
How can I get the processID created by popen to kill ?
My code is :
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
FILE *stream = _popen(commandOptimize, "r");
time_t starttime,currenttime;
time(&starttime);
if (stream){
while (!feof(stream))
{
if (fgets(buffer, MAX_LENGTH, stream) != NULL)
{
szBuffer += buffer;
}
time(¤ttime);
if(((int)(currenttime - starttime)) > m_timeoutcmd)
{
break;
}
}
}
_pclose(stream ); //problem here
There are several ways to get the processID for example "CreateProcess32Snapshot()" and Process32First + Process32Next to fill out a bunch of PROCESSENTRY32 structs or an ExecQuery() against all 'Win32_Process' entries where "name='x'". But none of them are the correct answer for what you are trying to accomplish. For what you want, do what kbw suggested and use CreateProcess() to launch the child process because it will fill out a PROCESS_INFORMATION struct when it executes and that will contain the process ID.
For what you want, do what kbw suggested and use CreateProcess() to launch the child process because it will fill out a PROCESS_INFORMATION struct when it executes and that will contain the process ID.
Sure,man.But the CreateProcess can not work with some shell commands such as : copy,echo ...
Another ways ?
Those are command in cmd.exe. To use them you'd need to use system(), or pass cmd.exe to CreateProcess(). I'd be surprised if you could use them wth popen().
You can invoke shell command using CreateProcess if you include cmd.exe in your command line in this sort of way
"cmd.exe /c copy example.txt copy.txt"
Which is just what the CRT code for _popen does. When you say "ping 8.8.8.8." it calls CreateProcess with "cmd.exe /c ping 8.8.8.8", for "echo "hello"" is says "cmd.exe /c echo "hello", etc.
Of course, _popen also makes it easier to read the program output, but that's another matter.