Opening Executables from Within a C Program
You may find yourself at times needing to execute external programs from within your own C application. While using system() may seem like a straightforward method, it poses certain risks and limitations. This article explores a more reliable approach using the CreateProcess() function.
Creating a New Process
The CreateProcess() function allows you to launch a new process and have it run independently from your calling application. Here's a sample implementation:
<code class="cpp">#include <windows.h> VOID startup(LPCTSTR lpApplicationName) { STARTUPINFO si; PROCESS_INFORMATION pi; ZeroMemory( &si, sizeof(si) ); si.cb = sizeof(si); ZeroMemory( &pi, sizeof(pi) ); CreateProcess( lpApplicationName, argv[1], NULL, NULL, FALSE, 0, NULL, NULL, &si, &pi ); CloseHandle( pi.hProcess ); CloseHandle( pi.hThread ); }</code>
This function takes the path to the executable as an argument and creates a new process for it. The process is then run independently.
Using CreateProcess() Effectively
In the example code, the argv[1] argument should contain the full path to the executable you want to launch. For instance, to execute "OpenFile.exe" located in the same directory as your own application:
<code class="cpp">startup( "OpenFile.exe" );</code>
Avoiding Errors
The error you encountered while using system() most likely resulted from not specifying the full path to the executable. CreateProcess() requires the absolute path to the target program to function correctly.
Conclusion
Using CreateProcess() is a more secure and reliable method for opening executables from within a C application. It allows you to control the execution environment and avoid potential security issues.
The above is the detailed content of How Can I Reliably Execute External Programs in C ?. For more information, please follow other related articles on the PHP Chinese website!