2018年7月7日土曜日

開発環境

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

長いエクササイズ(p. 460)

コード

Makefile

CC = cc

all: sample run

sample: sample.c
 $(CC) sample.c -o sample

run: sample
 ./sample
#include <errno.h>
#include <signal.h>
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <unistd.h>

int score = 0;

void end_game(int sig) {
  printf("\n最終得点: %i\n", score);
  exit(0);
}

typedef void (*fn_type)(int);
int catch_signal(int sig, fn_type 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, char *argv[]) {
  catch_signal(SIGALRM, times_up);
  catch_signal(SIGINT, end_game);
  srandom(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);
    }
  }
}

入出力結果(Terminal)

$ make
cc sample.c -o sample
./sample

4かける3はいくつですか?12

9かける0はいくつですか?0

5かける7はいくつですか?35

7かける8はいくつですか?56

10かける5はいくつですか?50

0かける0はいくつですか?
時間切れ!

最終得点: 5
$ make
./sample

1かける0はいくつですか?  C-c C-c
最終得点: 0

$ make
./sample

0かける7はいくつですか?1

間違いです!得点: 0

1かける8はいくつですか?1

間違いです!得点: 0

8かける3はいくつですか?  C-c C-c
最終得点: 0

$ 

0 コメント:

コメントを投稿