如何:每秒调用一个方法来实现 getchar() 或者如果它为空则继续

How to: call a method every second impleting getchar() or if it's empty then continue

所以我正在尝试做这样的事情:我有一个函数调用另一个函数,在这个函数中我从给定文件中逐行读取文本,我希望它执行它读取的内容(工作 atm),但是它应该每秒只执行一行,这样用户就有时间在标准输入中写一个 S,意思是停止(或类似的东西),否则如果用户没有输入任何内容,那么程序应该继续迭代文件。我该怎么做?

我一直用来尝试的是信号和警报(),测试如下:

#include<stdio.h>
#include<signal.h>
#include<unistd.h>
#include<string.h>

volatile int breakflag = 2;

void handle(int sig){
    if( getchar()=='a' ){
        printf("it read something from input\n");
        --breakflag;
    }else{
        printf("it didn't read anything from input\n"); 
        --breakflag;
    }
    alarm(2);
}

int main(){
    /*let's say this is part of the method that i call each iteration until I've read EOF.
    now is the part that i should execute whatever i get into the stdin,
    or if it's empty it should continue to next iteration...
    */
    signal(SIGALRM, handle);
    alarm(1);
    while(breakflag){
        sleep(1);
    }
    printf("done\n");

    return 0;
}

抱歉,描述太长了。但是我很难尝试得到任何有用的东西。 我找到了一些帮助我解决这个问题的答案,但我似乎无法按照我需要的方式解决它....

您可以使用 select,超时为 1 秒,例如:

#include <stdio.h>
#include <sys/select.h>

int main()
{
  struct timeval tv;
  fd_set fd;
  int i;

  FD_ZERO(&fd);

  for (i = 0; i != 10; ++i) {
    FD_SET(0, &fd);
    tv.tv_sec = 1;
    tv.tv_usec = 0;

    if (select(0 + 1, &fd, NULL, NULL, &tv) == -1) {
      perror("error on select");
      break;
    }
    if (FD_ISSET(0, &fd)) {
      int c = getchar();

      if (c == EOF) {
        puts("EOF");
        break;
      }
      printf("read char '%c'\n", c);
    }
    else
      puts("nothing to read");
  }

  return 0;
}

编译和执行(在Linux下):

pi@raspberrypi:/tmp $ gcc -Wall c.c
pi@raspberrypi:/tmp $ (sleep 2 ; echo -n a ; sleep 3 ; echo -n z) | ./a.out
nothing to read
nothing to read
read char 'a'
nothing to read
nothing to read
nothing to read
read char 'z'
EOF
pi@raspberrypi:/tmp $ ./a.out