如何重启一个控制台程序

作者:朱金灿

来源:http://blog.csdn.net/clever101

 

        在《VC实现程序重启的做法》一文中我介绍了如何重启一个GUI程序的做法,今天研究了一下如何重启一个控制台程序,发现其实也很简单,简而言之就是新建一个进程,然后杀死当前进程。下面是一个测试程序:


#include "stdafx.h"
#include <windows.h>
#include <string>  
using std::string;  
using std::wstring;  
#include "boost/algorithm/string.hpp"  
#include "boost/filesystem/path.hpp"  
#include "boost/filesystem/operations.hpp"  
#include "boost/format.hpp" 

int main(int argc, char* argv[])  
{  

  TCHAR szAppName[MAX_PATH];  
  :: GetModuleFileName(NULL, szAppName, MAX_PATH);  
  std::wstring strAppFullName = szAppName;

  // 假如不存在文件就创建文件并写入文件,假如存在文件就读取文件
  std::wstring strLog = strAppFullName.substr(0,strAppFullName.rfind('\')+1);
  strLog += std::wstring(_T("log.txt"));
  FILE * fp = NULL;
  // 这里用到了boost库的文件系统接口
  if(!boost::filesystem::exists(strLog))
  {
	  if( (fp  = _tfopen(strLog.c_str(),_T("w"))) != NULL )
		  puts ("create log file successful!");
  }
  else
  {
	  if( (fp  = _tfopen(strLog.c_str(),_T("r"))) != NULL )
		  puts("open log file successful!");
  }

  // 新建一个进程
  STARTUPINFO StartInfo;  
  PROCESS_INFORMATION procStruct;  
  memset(&StartInfo, 0, sizeof(STARTUPINFO));  
  StartInfo.cb = sizeof(STARTUPINFO);  
  ::CreateProcess(  
	  strAppFullName.c_str(),  
	  NULL,  
	  NULL,  
	  NULL,  
	  FALSE,  
	  NORMAL_PRIORITY_CLASS,  
	  NULL,  
	  NULL,  
	  &StartInfo,  
	  &procStruct);  

  // 关闭当前进程
  HWND hWnd = ::FindWindow(NULL,szAppName);
  ULONG nProcessID;
  ::GetWindowThreadProcessId( hWnd, &nProcessID );
  HANDLE hProcessHandle = ::OpenProcess( PROCESS_TERMINATE, FALSE,nProcessID );
  ::TerminateProcess( hProcessHandle, 4 );
   return 0;  
}   




原文地址:https://www.cnblogs.com/lanzhi/p/6470538.html