開発環境
- OS: macOS High Sierra - Apple
- IDE(統合開発環境): Xcode - Apple
- プログラミング言語: C
Head First C ―頭とからだで覚えるCの基本 (David Griffiths (著)、Dawn Griffiths (著)、中田 秀基 (監修)、木下 哲也 (翻訳)、オライリージャパン)の11章(プロセス間通信 - お話は楽しい)、自分で考えてみよう(p. 487)を取り組んでみる。
自分で考えてみよう(p. 487)
// // main.c // sample1 // // Created by kamimura on 2018/02/26. // Copyright © 2018 kamimura. All rights reserved. // #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <string.h> #include <errno.h> #include <signal.h> #include <stdbool.h> #include <time.h> int score = 0; void end_game(int sig) { printf("\n最終得点: %i\n", score); exit(0); } typedef void (*fn_handler)(int); int catch_signal(int sig, fn_handler handler) { struct sigaction action; action.sa_handler = handler; sigemptyset(&action.sa_mask); action.sa_flags = 0; return sigaction(sig, &action, NULL); } void times_up(int sig) { puts("\n時間切れ!"); raise(SIGINT); } void error(char *msg) { fprintf(stderr, "%s: %s\n", msg, strerror(errno)); exit(1); } int main(int argc, const char * argv[]) { catch_signal(SIGALRM, times_up); catch_signal(SIGINT, end_game); srandom((int)time(0)); while (true) { int a = random() % 11; int b = random() % 11; char txt[4]; alarm(5); printf("\n%iかける%iはいくつですか?", a, b); fgets(txt, 4, stdin); int answer = atoi(txt); if (answer == a * b) { score++; } else { printf("\n間違いです!得点: %i\n", score); } } return 0; }
入出力結果(Terminal)
$ ./server 接続を待っています。 C-c C-cさようなら! $
0 コメント:
コメントを投稿