I need a shell_exec function in PHP with the timeout support but apparently, there is none unless you write one. It is possible to write one on Linux OS, which makes uses of various command line tool. But on Windows, it seems not so convenient to come up with one. Therefore, the following presents the small tool (32-bit) written in C++, compiled using GNU C++ compiler for windows platform.
We need the Win32 API CreateProcess to launch a command in a separate process. We also need the WaitForSingleObject to wait the process infinitely or giving it a timeout period in miliseconds. If the WaitForSingleObject returns WAIT_TIMEOUT, it means that the process is still running after the timeout period, then we need the KillProcessById to kill it.
int run(char* command, int ms) {
STARTUPINFO si;
PROCESS_INFORMATION pi;
ZeroMemory( &si, sizeof(si) );
si.cb = sizeof(si);
ZeroMemory( &pi, sizeof(pi) );
if( !CreateProcess( NULL, // No module name (use command line)
command, // 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
)
{
printf( "CreateProcess failed (%d).\n", GetLastError() );
return -2;
}
// Wait until child process exits.
if (ms == 0) {
WaitForSingleObject( pi.hProcess, INFINITE );
} else {
DWORD rtn = WaitForSingleObject( pi.hProcess, ms);
if (rtn == WAIT_TIMEOUT) {
KillProcessById(pi.dwProcessId);
}
}
// Close process and thread handles.
CloseHandle( pi.hProcess );
CloseHandle( pi.hThread );
return 0;
}
The full C++ code is on github. And you will need to define the KillProcessById in this post. The command line usage will be something like this:
timeout "notepad 123" 3000
Download Pre-compiled Binary
Pre-compiled Binary for Win32 (zipped 4KB)
–EOF (The Ultimate Computing & Technology Blog) —
441 wordsLast Post: The Golden Rules of Removing Duplicate Pages by Using NoIndex or Canonical
Next Post: How to Read File Content from URL with Time out in PHP?
