You are here:

C++/Running program within source code

Advertisement


Question
I am trying to get my program to run a separate application elsewhere on my system.  After I run the seprate application I want my original prgram to close.  How do I do it? I have Visual Studio.Net 2003 C++.  Thanks for your time.

Answer
Mark, Thank you for your question.

To run a program, call the CreateProcess function. You can then get a handle to the new process via the 'lpProcessInformation' argument. Using this handle, call the WaitForSingleObject function to wait until the process exits. This should work under all versions of Windows except for Win 3.x (obsolete) Windows.

Here is some source code to show one way to solve your problem. IMPORTANT NOTE: This Windows code may not compile because it is dependent on other parts of my personal application library. It should be sufficient to give you some ideas; I cannot supply you with all of the source code needed to make this example actually work. Note the failure of AllExperts.com to provide for indenting source code.

//   ----------------------------------------------------------------------------
//   Name:         function Run
//
//   Description:   Execute a given command line in the Windows environment.
//          Optionally, return without waiting for the command to exit.
//          If error, return FALSE. See 'CApp::GetCmdForShellFile'.
//
//   Caution:      If the command is executed asynchronously, and pProcess is
//          given, the caller must call CloseHandle on *pProcess.
//   ----------------------------------------------------------------------------
BOOL          Run(PCSTR CmdLine, int/*RUN_TYPE*/ Flags /*= RUN_DEFAULT*/,
         HANDLE * pProcess/* = NULL */,
         DWORD * pProcessID/* = 0 */)
  {
  HANDLE          Process;
  UINT          Status;
  char          sTemp[512];
  STARTUPINFO       StartupInfo;
  PROCESS_INFORMATION ProcessInfo;
  DWORD          ErrCode;

  CLEAR(StartupInfo);
  CLEAR(ProcessInfo);
  StartupInfo.cb = sizeof(STARTUPINFO);
  if (IS_FLAG_SET_IN_ARG(RUN_MAXIMIZED))
     {
     StartupInfo.dwFlags = STARTF_USESHOWWINDOW;
     StartupInfo.wShowWindow = SW_SHOWMAXIMIZED;
     }
  if (IS_FLAG_SET_IN_ARG(RUN_MINIMIZED))
     {
     StartupInfo.dwFlags = STARTF_USESHOWWINDOW;
     StartupInfo.wShowWindow = SW_SHOWMINIMIZED;
     }
  Process = INVALID_HANDLE_VALUE;

  // Execute command
  StartupInfo.cb = sizeof(STARTUPINFO);
  StartupInfo.lpTitle = (char *)CmdLine;
  Status = CreateProcess(NULL, (char *)CmdLine, NULL, NULL,
     FALSE, 0, NULL, NULL, &StartupInfo, &ProcessInfo);
  if (!Status)
     {
     ErrCode = GetLastError();
     if (IS_FLAG_SET_IN_ARG(RUN_NOMSG))
        return FALSE;
     if (ErrCode == 0)
        Box("*System is out of resources.");
     else if (ErrCode == ERROR_BAD_FORMAT)
        Box("*Invalid EXE format for command %s.", CmdLine);
     else if (ErrCode == ERROR_FILE_NOT_FOUND)
        Box("!The EXE file was not found for command %s.",
         CmdLine);
     else if (ErrCode == ERROR_PATH_NOT_FOUND)
        Box("!The EXE path was not found for command %s.",
         CmdLine);
     else
        {
        GetSystemErrMsg(ErrCode, sTemp);
        // Sys err msg might have embedded % specifiers
        Box("!Windows reported error '%s' (Error code %ld/0x%lx) "
         "on attempting to run command %s.", sTemp, ErrCode, ErrCode,
         CmdLine);
        }
     return FALSE;
     } // Error occurred

  Process = ProcessInfo.hProcess;
  if (Process)
     CloseHandle(ProcessInfo.hThread);
  else
     {
     TRACE("*** Process handle is NULL. (Run)");
     Process = INVALID_HANDLE_VALUE;
     }

  if (IS_FLAG_SET_IN_ARG(RUN_ASYNC))
     {
     if (pProcess)
        (*pProcess) = Process;
     else
        CloseHandle(Process);
     if (pProcessID)
        (*pProcessID) = ProcessInfo.dwProcessId;
     return TRUE;
     } // Async run

  // (Sync run)

  //WaitForInputIdle((*pProcess), 1000);
  WaitForSingleObject(Process, INFINITE);

  if (Process != INVALID_HANDLE_VALUE)
     CloseHandle(Process);
  if (pProcess)
     (*pProcess) = INVALID_HANDLE_VALUE;
  if (pProcessID)
     (*pProcessID) = 0;
  return TRUE;
  } // Run

David Spector

C++

All Answers


Answers by Expert:


Ask Experts

Volunteer


David Spector

Expertise

Highly knowledgeable in the C++ language, Visual C++ (MSVC), Windows API, documentation and other quality-assurance techniques, and debugging. Knowledgeable in MFC, COM, GUI design, and object-oriented design.

Experience

I have been a software engineer since 1965. I have been published. My specializations have been: biomedical programming, compiler implementation, and many kinds of Windows programming. I don't do Databases or other business-oriented stuff.

Publications
Windows?/DOS Developer's Journal, ACM SIGPLAN Notices, and Computer Science Press.

Education/Credentials
ICCP Systems Programming Certification
Master's degree equivalent in Computer Science

©2016 About.com. All rights reserved.