C, C++

명령창(cmd)을 열지 않고 명령 실행하고 결과 받아오기 popen(pipe open), pclose(pipe close)

J-sean 2025. 4. 14. 11:48
반응형

콘솔 윈도우(cmd)를 열지 않은 상태에서 명령을 실행하고 결과를 읽고 출력해 보자.

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
#include <stdio.h>
#include <stdlib.h>
 
int main(void)
{
    char psBuffer[128];
    FILE* pPipe;
 
    // Run command so that it writes its output to a pipe. Open this
    // pipe with read text attribute so that we can read it
    // like a text file.
    if ((pPipe = _popen("wmic baseboard get manufacturer, product, serialnumber""rt")) == NULL)
    {
        exit(1);
    }
 
    /* Read pipe until end of file, or an error occurs. */
    while (fgets(psBuffer, 128, pPipe))
    {
        puts(psBuffer);
    }
 
    int endOfFileVal = feof(pPipe);
    int closeReturnVal = _pclose(pPipe);
 
    if (endOfFileVal)
    {
        printf("\nProcess returned %d\n", closeReturnVal);
    } else
    {
        printf("Error: Failed to read the pipe to the end.\n");
    }
}
 

 

 

메인보드 정보가 출력된다.

 

아래와 같은 결과가 나온다면 wmic.exe를 프로젝트 폴더에 복사해 넣으면 된다.

'wmic'은(는) 내부 또는 외부 명령, 실행할 수 있는 프로그램, 또는 배치 파일이 아닙니다.

Process returned 1

 

반응형