"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > How to Launch Executables from C++: A Safer Alternative to `system()`?

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

Published on 2024-11-14
Browse:597

  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.

#include 

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);
}

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

Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3