Home  >  Article  >  Backend Development  >  How to Launch Executables from C : A Safer Alternative to `system()`?

How to Launch Executables from C : A Safer Alternative to `system()`?

Barbara Streisand
Barbara StreisandOriginal
2024-11-02 01:21:02168browse

  How to Launch Executables from C  :  A Safer Alternative to `system()`?

Launching Executables from C : An Alternative to system()

In C , launching an executable from another executable can be achieved using the system() function, but this method poses security and system efficiency concerns. A more robust approach involves utilizing the CreateProcess() function.

<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>

Using CreateProcess():

  1. Define the startup() function as shown above.
  2. Specify the path to the executable in lpApplicationName.
  3. Call CreateProcess() to launch the executable.
  4. Close process and thread handles for resource cleanup.

Error Troubleshooting:

Ensure that the specified path to the executable is correct. The error encountered in the provided code is likely due to an invalid path to "OpenFile.exe".

The above is the detailed content of How to Launch Executables from C : A Safer Alternative to `system()`?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn