Linux/실용 소스

Pipe 통신 예제

제이Lee 2023. 7. 25. 17:32

간단하게 pwd 명령을 소스로 실행하고

그에 관한 response를 출력하는 프로그램의 예제이다.

 

프로그램 내에서 명령어를 실행하고

response 값을 받아와 처리해야 하는 경우가 은근히 많이 발생하기 때문에

유용하게 사용하는 경우가 많이 있다.

#include <stdlib.h>
#include <stdio.h>
using namespace std;

int main() {

   FILE *fp;
   char buf[256];

   fp = popen("pwd", "r");
   if (fp == NULL) {
     fprintf(stderr, "popen error");
     exit(1);
   }

   if (fgets(buf, sizeof(buf), fp) == NULL) {
     fprintf(stderr, "No Data");
     exit(1);
   }

   printf("Result : %s", buf);
   pclose(fp);

   return 0;
}

 

결과값