Tuesday, July 7, 2015

eng,c++> launching multiple console

It is being edited

#include  <stdio.h>
#include  <iostream>
#include  <windows.h>
#include  <string>

int main(int argc, char* argv[]){
 SetConsoleTitle(argv[0]);
 std::string slot_name = "\\\\.\\mailslot\\" + std::string(argv[0]);
 char buff[100];
 HANDLE h_mailslot = CreateMailslot(slot_name.c_str(), 0, MAILSLOT_WAIT_FOREVER, NULL);
 if(h_mailslot == INVALID_HANDLE_VALUE){
  printf("Unable to create mailslot!\n");
  throw 1;
 }
 while(1){
  DWORD n_byte;
  if(!ReadFile(h_mailslot, buff, sizeof(buff), &n_byte, NULL))
   break;
   buff[n_byte / sizeof(char)] = 0;
   if(strcmp(buff, "exit")==0)
       break;
   printf("%s", buff);
 }
 CloseHandle(h_mailslot);
 return 0;
}
console.exe

#include  <stdio.h>
#include  <iostream>
#include  <windows.h>
#include  <process.h>
#include  <direct.h>

std::string getExePath(){
 char buffer[MAX_PATH];
 GetModuleFileName(NULL, buffer, MAX_PATH);
 std::string str(buffer);
 std::string::size_type pos = str.find_last_of("\\/");
 return str.substr(0, pos);
}

class Console {
public:
 Console(std::string title = "debug"){
  STARTUPINFO info = { sizeof(info) };
  PROCESS_INFORMATION process_info;
  std::string filepath = getExePath() + "\\console.exe";
  if(!CreateProcess(filepath.c_str(), const_cast <char *>(title.c_str()), NULL, NULL, false, CREATE_NEW_CONSOLE, NULL, NULL, &info, &process_info)){
   printf("CreateProcess() failure.\n");
   throw 1;
  }
  h_cmd_process = process_info.hProcess;
  Sleep(1000); // waiting for process
  std::string slot_name = "\\\\.\\mailslot\\" + title;
  h_mailslot = CreateFile(slot_name.c_str(), GENERIC_WRITE, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
  if(h_mailslot == INVALID_HANDLE_VALUE){
   printf("Unable to create mailslot %d\n", GetLastError());
   throw 1;
  }
 }
 void print(const std::string& message){
  DWORD exitCode;
  GetExitCodeProcess(h_cmd_process, &exitCode);
  if(exitCode != STILL_ACTIVE) {
   //task exited with code exitCode
  }
  DWORD n_byte;
  if(!WriteFile(h_mailslot, message.c_str(), message.length()*sizeof(char), &n_byte, NULL)){
  }
 }
 ~Console(){
  print("exit");
  //TerminateProcess(h_cmd_process, 0);
  CloseHandle(h_mailslot);
 }
private:
 HANDLE h_cmd_process;
 HANDLE h_mailslot; 
};

void main(){
    Console console;
    for(int i = 0; i  < 10; i++){
        std::string message = "hello hell? " + std::to_string((_ULonglong)i) + "\n";
        console.print(message);
    }
    getchar();
}

client.exe

Class Consoles launch process "console.exe" when it is created. It send string by mailslot(msdn). The "client.exe" should be launched as administrator.

No comments:

Post a Comment