開発環境
- OS: macOS High Sierra - Apple
- IDE(統合開発環境): Xcode - Apple
- プログラミング言語: C
Head First C ―頭とからだで覚えるCの基本 (David Griffiths (著)、Dawn Griffiths (著)、中田 秀基 (監修)、木下 哲也 (翻訳)、オライリージャパン)の10章(プロセス間通信 - お話は楽しい)、エクササイズ(p. 447)を取り組んでみる。
エクササイズ(p. 447)
// // main.c // sample1 // // Created by kamimura on 2018/02/26. // Copyright © 2018 kamimura. All rights reserved. // #include <stdio.h> #include <stdlib.h> #include <string.h> #include <errno.h> #include <unistd.h> #include <sys/wait.h> void error(char *msg) { fprintf(stderr, "%s: %s\n", msg, strerror(errno)); exit(1); } void open_url(char *url) { pid_t pid = fork(); if (pid == -1) { error("プロセスをフォークできません"); } if (!pid) { if (execlp("open", "open", url, NULL) == -1) { char s[255]; sprintf(s, "'%s'を開けません", url); error(s); } } int pid_status; if (waitpid(pid, &pid_status, 0) == -1) { error("子プロセスの待機エラー"); } } int main(int argc, const char * argv[]) { char *phrase = (char*)argv[1]; char *vars[] = { "RSS_FEED=http://rss.cnn.com/rss/edition.rss", NULL }; int fd[2]; if (pipe(fd) == -1) { error("パイプを作成できません"); } pid_t pid = fork(); if (pid == -1) { error("プロセスをフォークできません"); } if (!pid) { close(fd[0]); if (dup2(fd[1], 1) == -1) { error("標準出力をリダイレクトできません"); } if (execle("/usr/bin/python", "/usr/bin/python", "rssgossip.py", "-u", phrase, NULL, vars) == -1) { error("スクリプトを実行できません"); } } close(fd[1]); if (dup2(fd[0], 0) == -1) { error("標準入力をリダイレクト出来ません"); } char line[255]; while(fgets(line, 255, stdin)) { printf("%s", line); if (line[0] == '\t') { open_url(line + 1); } } int pid_status; if (waitpid(pid, &pid_status, 0) == -1) { error("子プロセスの待機エラー"); } return 0; }
入出力結果(Terminal)
$ ./news Traceback (most recent call last): File "rssgossip.py", line 50, in <module> searcher = re.compile(args[0], re.IGNORECASE) IndexError: list index out of range $ ./news Japan $ ./news US President or Emperor? Xi pushes China back to one-man rule https://www.cnn.com/2018/02/26/asia/china-xi-jinping-president-intl/index.html North Korea 'willing to hold talks' but US plays coy https://www.cnn.com/2018/02/25/asia/north-korea-us-talks-intl/index.html Axios: Trump pushing to have personal pilot run FAA https://www.cnn.com/2018/02/25/politics/trump-pilot-faa-nomination/index.html No one knows who this unconscious Syrian toddler is https://www.cnn.com/2018/02/23/middleeast/syria-eastern-ghouta-lost-child-intl/index.html Fear of Russian aggression driving US military sales to Europe https://www.cnn.com/2018/02/24/politics/fear-russia-aggression-driving-us-military-sales/index.html US Supreme Court to hear digital privacy case with global impact http://money.cnn.com/2018/02/25/technology/microsoft-us-supreme-court-data-sharing/index.html USA Swimming officials under fire for alleged culture of abuse https://www.cnn.com/2018/02/24/us/usa-swimming-abuse-allegations/index.html Stolen work by famed painter Degas found in bus https://www.cnn.com/2018/02/23/world/stolen-degas-painting-found-bus-intl/index.html $
0 コメント:
コメントを投稿