アットウィキロゴ

外部プログラムの呼び出し

C言語から外部プログラムを呼び出す

systemを使う方法


popenを使う方法

外部プログラムを実行した結果、そのプログラムが標準出力等に出力した情報を使う場合は、popenが使える。

perlプログラムをCから呼び出す例:

サンプルperlプログラム
test.pl
-----
#! bin/perl

print "1 2 test\n"
-----
(結果)
1 2 test

C側の呼び出しプログラム
caller.c
-----
#include <stdio.h>

int main(int argc, char* argv[])
{
  FILE* fp = NULL;
  int a,b;
  char str[256];
  char line[256];

  fp = popen ("./test.pl", "r");
  fgets(line, sizeof(line), fp);
  sscanf(line, "%d %d %s", &a, &b, str);
  printf("a=%d, b=%d, str=%s\n",a, b, str);
  pclose(fp);

  return 0;
}
-----
(結果)
a=1, b=2, str=test

タグ:

program linux
最終更新:2009年12月09日 16:00