Home > Backend Development > C++ > body text

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

Barbara Streisand
Release: 2024-11-02 01:21:02
Original
167 people have browsed it

  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>
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!