C++ popen command without console

2019-01-27 21:03发布

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

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

I am using Visual C++ and want to make an Library to return the output of some command, say, dir.

3条回答
祖国的老花朵
2楼-- · 2019-01-27 21:28

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 should off course check return values etc...

查看更多
再贱就再见
3楼-- · 2019-01-27 21:42

I needed to solve this for my full screen OpenGL Windows application, but was unable to prevent the console window popping up. Instead, taking back focus after a short delay seems to work well enough to avoid seeing it.

_popen(cmd, "wb");

Sleep(100);

ShowWindow(hWnd, SW_SHOWDEFAULT);
SetForegroundWindow(hWnd);

Update: this apparently doesn't work if the program is launched from Explorer. It is working when launched from Visual Studio.

查看更多
Lonely孤独者°
4楼-- · 2019-01-27 21:47

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

CreatePipe() to create the pipes necessary to communicate, and CreateProcess to create the 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 more than get you on your way to doing what you wish to accomplish.

查看更多
登录 后发表回答