"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 Executable Files Securely in C++: Why CreateProcess() Is Your Best Choice?

How to Launch Executable Files Securely in C++: Why CreateProcess() Is Your Best Choice?

Published on 2024-11-08
Browse:695

How to Launch Executable Files Securely in C  : Why CreateProcess() Is Your Best Choice?

Utilizing CreateProcess() to Launch Executable Files

In this guide, we'll explore how to open an executable file (.exe) from within another C executable.

The Pitfalls of Using system()

Before delving into the solution, it's crucial to highlight the dangers of employing the system() function. System() exhibits several drawbacks:

  • It's ресурсоёмким, potentially slowing down your program.
  • It undermines security, as you have no control over the executed commands. This can lead to unintentionally running malicious programs with administrator privileges.
  • It's often flagged as a security threat by antivirus software.

Employing CreateProcess()

Instead of system(), we recommend utilizing the CreateProcess() function. This function allows you to launch an executable file, creating an independent process.

#include 

VOID startup(LPCTSTR lpApplicationName)
{
  STARTUPINFO si;     
  PROCESS_INFORMATION pi;

  ZeroMemory( &si, sizeof(si) );
  si.cb = sizeof(si);
  ZeroMemory( &pi, sizeof(pi) );

  CreateProcess( lpApplicationName,   // executable path
                 argv[1],        // command line
                 NULL,           // process handle not inheritable
                 NULL,           // thread handle not inheritable
                 FALSE,          // no handle inheritance
                 0,              // no creation flags
                 NULL,           // parent's environment block
                 NULL,           // parent's starting directory 
                 &si,            // STARTUPINFO structure
                 &pi             // PROCESS_INFORMATION structure
                 );

  // Close process and thread handles. 
  CloseHandle( pi.hProcess );
  CloseHandle( pi.hThread );
}

Resolving the Error

The error you encountered likely stems from the fact that you didn't specify the full path of the executable file. Ensure that you provide the complete path, including the file name.

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