2011-08-15 3 views
8

popen을 사용하여 명령의 출력을 가져올 때, 예를 들어 dir이라고 말하면 콘솔이 프롬프트됩니다.콘솔이없는 C++ popen 명령

그러나 콘솔의 모양없이 명령의 출력을 얻을 수 있습니까?

Visual C++를 사용하고 있고 일부 명령 (예 : dir)의 결과를 반환하도록 라이브러리를 만들고 싶습니다. POSIX와

+4

어떤 플랫폼/툴체인을 사용하고 있습니까? – Flexo

+2

어떤 OS를 사용하고 있습니까? 이것은 적절한 OS에서 발생하지 않습니다. 리눅스,하지만 아마도 당신은 예를 들면. Windows에서 Cygwin을 사용 하시겠습니까? –

+0

이것이 Windows 인 경우 (그리고 저는 수년 동안이 수많은 시간에 걸쳐 싸웠 기 때문에 100 % 확신합니다), 유일하게 신뢰할 수있는 방법은 CreateProcess입니다. 다른 대부분의 라이브러리는 하위 콘솔이 열리지 않도록 필요한 플래그를 건너 뜁니다. –

답변

2

가이 같은해야한다 : 당신은 오프 물론 반환 값 등을 확인해야합니다

//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); 

...

+0

파이프 란 무엇입니까? Visual Studio에서이 단어를 강조 표시했습니다. – user883434

+0

포함해야 할 라이브러리가 있습니까? – user883434

+0

그 유형을 모르는 몇 가지 변수가 있습니다 ... – user883434

5

윈도우 가정 (이 동작은 발병 곳은 유일한 플랫폼이기 때문에) :

CreatePipe() 통신에 필요한 파이프를 만들고, CreateProcess 자식 프로세스를 만듭니다.

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); 

달성하려는 작업을 수행하는 것 이상의 의미가 있습니다.

+2

죄송합니다. 필요한 도서관은 무엇입니까? – user883434

+0

MSDN 설명서에 대한 링크는 포함 할 헤더와 라이브러리를 정확하게 알려주지 만이 경우 라이브러리는 WIN32 kernel32 라이브러리입니다. –

+0

유용하지만 다른 플래그를 사용해야 작동합니다. 참조 : http://stackoverflow.com/a/16953192/453673 – Nav

1

내 전체 화면 OpenGL Windows 응용 프로그램을 위해이 문제를 해결해야했지만 콘솔 창이 나타나지 않도록 할 수 없었습니다. 대신, 짧은 지연 후에 초점을 되 찾는 것은 그것을 보는 것을 피할만큼 충분히 잘 작동하는 것처럼 보입니다.

_popen(cmd, "wb"); 

Sleep(100); 

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

업데이트 : 프로그램이 탐색기에서 실행되면 분명히 작동하지 않습니다. Visual Studio에서 시작할 때 작동합니다.