Programming/C

popen 함수

moxie2ks 2025. 3. 19. 18:01
728x90
반응형

개요

popen() 함수는 C언어에서 외부 프로세스를 실행하고 해당 프로세스의 입출력 스트림에 접근할 수 있는 강력한 시스템 호출이다. 이 함수는 shell 명령어를 실행하고 그 결과를 파이프를 통해 읽거나 쓸 수 있게 해준다. 주로 Unix 및 Linux 시스템에서 사용되며, 시스템 명령을 실행하고 그 출력을 프로그램 내에서 처리해야 할 때 유용하다. 본 글에서는 popen() 함수의 기본 원리, 구문, 사용 사례를 살펴보고자 한다.

예제 코드

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define MAX_BUFFER_SIZE 1024

int execute_command(void)
{
    FILE *fp;
    char command[] = "/bin/bash -c \\"echo -n 'HELLO WORLD'\\"";
    unsigned char command_result_buffer[MAX_BUFFER_SIZE] = {0};

    // Execute openssl command
    if ((fp = popen(command, "r")) == NULL)
    {
        perror("popen error");
        return EXIT_FAILURE;
    }

    // Get result
    size_t bytesRead = fread(command_result_buffer, 1, sizeof(command_result_buffer) - 1, fp);
    if (bytesRead == 0)
    {
        if (feof(fp))
            printf("End of file reached\\n");
        else if (ferror(fp))
            perror("fread error");
        
        pclose(fp);
        return EXIT_FAILURE;
    }

    command_result_buffer[bytesRead+1] = '\\0'; // Null-terminate the result string
    printf("Result(%s), len(%zu)\\n", command_result_buffer, bytesRead);

    // Terminate process and release resources.
    if (pclose(fp) == -1)
    {
        perror("pclose error");
        return EXIT_FAILURE;
    }
    
    return EXIT_SUCCESS;
}

int main(void)
{
    execute_command();
    
    return 0;
}

코드 설명

  • command 변수에 echo 커맨드 저장.
    • echo의 -n 파라미터(줄넘김 포함 안함)를 사용하기 위해서는 /bin/bash -c 옵션을 반드시 추가 후 사용해야 한다.
char command[] = "/bin/bash -c \\"echo -n 'HELLO WORLD'\\"";
  • 저장한 command 변수를 popen으로 실행
// Execute openssl command
if ((fp = popen(command, "r")) == NULL)
{
    perror("popen error");
    return EXIT_FAILURE;
}
  • 실행 결과와 실행결과의 size를 저장
// Get result
size_t bytesRead = fread(command_result_buffer, 1, sizeof(command_result_buffer) - 1, fp);
if (bytesRead == 0)
{
    if (feof(fp))
        printf("End of file reached\\n");
    else if (ferror(fp))
        perror("fread error");
    
    pclose(fp);
    return EXIT_FAILURE;
}
  • 결과 출력
    • 결과 문자열의 마지막에 ‘\0’ 처리 필요
    command_result_buffer[bytesRead+1] = '\\0'; // Null-terminate the result string
    printf("Result(%s), len(%zu)\\n", command_result_buffer, bytesRead);
  • pclose를 호출하여 pipe 정상 종료
// Terminate process and release resources.
if (pclose(fp) == -1)
{
    perror("pclose error");
    return EXIT_FAILURE;
}

참조

popen(3), pclose(3)의 활용 - 다른 프로세스의 표준 입/출력 제어하기

728x90
반응형