2018年7月5日木曜日

開発環境

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

入出力結果(Terminal)

$ cc sample.c -o newshound2
$ ./newshound2 us
$ cat stories.txt 
Amesbury victims poisoned by same nerve agent used on ex-spy 
Jaguar Land Rover: Brexit will cost us $1.6B
Kim Dotcom can be extradited to the US, New Zealand court rules
UK probes alleged Russian links to Brexit campaign
Police find 'items of interest' at property linked to suspected serial killer
Half the US thinks Donald Trump is a racist
Houston streets flood after heavy rains, sparking memories of Harvey
Experience the world's largest waterfall cluster
Merkel: US auto tariffs could start trade war
Dubious Fox News article appears to have sparked Trump attack on Obama
Moms on conditions at US immigration detention facilities: 'They treated us as though we were animals'
Airbus unveils new Beluga XL
$ 

0 コメント:

コメントを投稿