2018年4月29日日曜日

開発環境

Head First C ―頭とからだで覚えるCの基本 (David Griffiths (著)、Dawn Griffiths (著)、中田 秀基 (監修)、木下 哲也 (翻訳)、オライリージャパン)の10章(プロセス間通信 - お話は楽しい)、自分で考えてみよう(p. 435)を取り組んでみる。

自分で考えてみよう(p. 435)

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

void error(char *msg) {
  fprintf(stderr, "%s: %s\n", msg, strerror(errno));
  exit(1);
}

int main(int argc, char *argv[]) {
  FILE *f = fopen("stories.txt", "w");
  if (!f) {
    error("stories.txtを開けません");
  }
  char *phrase = argv[1];
  char *vars[] = {"RSS_FEED=http://rss.cnn.com/rss/edition.rss", NULL};
  pid_t pid = fork();
  if (pid == -1) {
    error("プロセスをフォークできません");
  }
  if (!pid) {
    if (dup2(fileno(f), 1) == -1) {
      error("標準出力をリダイレクトできません");
    }
    if (execle("/usr/bin/python", "/usr/bin/python", "rssgossip.py", phrase,
               NULL, vars) == -1) {
      error("スクリプトを実行できません");
    }
  }
}

入出力結果(Terminal)

$ cc sample.c -o sample
$ ./sample US
$ cat stories.txt 
Thousands protest in Pamplona over bull run gang rape case
Trump slams 'lousy' London embassy again
Trump threatens US government shutdown over border security
Trump on Kremlin ties to Russian lawyer 
3 US Marines charged with rape
Who is Meghan Markle's future husband?
The Gaia satellite gave us a new star map that is out of this world
Superstitions of rich and famous
North Korean leader said he's 'not the kind of person' to fire nuclear weapons at US, South Korea says
US increases tracking of N Korea ahead of Trump-Kim meeting
Waffle House victim died singing gospel
$