C ++ command console without console

when I use popen to get the output of a command, say dir, it will output the console.

however, can I get the output of the command without the console appearing?

I use Visual C ++ and want the library to return the output of some command, say dir.

+8
c ++ command popen console
source share
3 answers

Assuming Windows (as this is the only platform where this behavior is endemic):

CreatePipe () to create the pipes necessary for communication, and CreateProcess to create a child process.

HANDLE StdInHandles[2]; HANDLE StdOutHandles[2]; HANDLE StdErrHandles[2]; CreatePipe(&StdInHandles[0], &StdInHandles[1], NULL, 4096); CreatePipe(&StdOutHandles[0], &StdOutHandles[1], NULL, 4096); CreatePipe(&StdErrHandles[0], &StdErrHandles[1], NULL, 4096); STARTUPINFO si; memset(&si, 0, sizeof(si)); /* zero out */ si.dwFlags = STARTF_USESTDHANDLES; si.hStdInput = StdInHandles[0]; /* read handle */ si.hStdOutput = StdOutHandles[1]; /* write handle */ si.hStdError = StdErrHandles[1]; /* write handle */ /* fix other stuff in si */ PROCESS_INFORMATION pi; /* fix stuff in pi */ CreateProcess(AppName, commandline, SECURITY_ATTRIBUTES, SECURITY_ATTRIBUTES, FALSE, CREATE_NO_WINDOW |DETACHED_PROCESS, lpEnvironment, lpCurrentDirectory, &si, &pi); 

This should help you do more that you want to accomplish.

+5
source share

With POSIX, it should be something like this:

 //Create the pipe. int lsOutPipe[2]; pipe(lsOutPipe); //Fork to two processes. pid_t lsPid=fork(); //Check if I'm the child or parent. if ( 0 == lsPid ) {//I'm the child. //Close the read end of the pipe. close(lsOutPipe[0]); //Make the pipe be my stdout. dup2(lsOutPipe[1],STDOUT_FILENO); //Replace my self with ls (using one of the exec() functions): exec("ls"....);//This never returns. } // if //I'm the parent. //Close the read side of the pipe. close(lsOutPipe[1]); //Read stuff from ls: char buffer[1024]; int bytesRead; do { bytesRead = read(emacsInPipe[0], buffer, 1024); // Do something with the read information. if (bytesRead > 0) printf(buffer, bytesRead); } while (bytesRead > 0); 

You must turn off checking return values, etc.

+2
source share

I needed to solve this for my full-screen OpenGL Windows application, but could not prevent the console window from appearing. Instead, capturing focus after a short delay seems to work well enough not to see it.

 _popen(cmd, "wb"); Sleep(100); ShowWindow(hWnd, SW_SHOWDEFAULT); SetForegroundWindow(hWnd); 

Update: this does not seem to work if the program is launched from Explorer. It works on startup from Visual Studio.

+1
source share

All Articles