1

how can I get user string input while the program is running? I want to break the while loop when user input "stop" to terminal. However, scanf or gets just wait for the input.

This is just an example that I want.

#include <stdio.h>
int main() {
    int i=0;
    while (1) {
        //if ( userinput == "stop") break; 
        printf("printing..%d\n",i++);
    }
    return 0;
}
Sieun Sim
  • 71
  • 5
  • 1
    You can start another thread that will watch the terminal. – DYZ Dec 06 '18 at 15:55
  • 1
    You can't do this with standard C. You need some sort of non-standard library like ncurses, Windows API, thread libraries etc. – Lundin Dec 06 '18 at 15:56
  • @DYZ Thanks, how can it watch the terminal? – Sieun Sim Dec 06 '18 at 16:03
  • 2
    Possible duplicate of [C non-blocking keyboard input](https://stackoverflow.com/questions/448944/c-non-blocking-keyboard-input) – DYZ Dec 06 '18 at 16:13

1 Answers1

3

You can do it with fork() and kill(), child process handle printf(), parent process handle userinput, when user input stop, parent process kill child process.

The following code could work:

#include <stdio.h>
#include <signal.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <string.h>
#include <unistd.h>

int main() {
  pid_t child_pid = fork();
  if (child_pid == 0) { // child
    int i = 0;
    for (;;) {
      printf("printing..%d\n", i++);
    }
  } else {
    char userinput[1024];
    for (;;) {
      fgets(userinput, sizeof(userinput), stdin);
      if (strcmp(userinput, "stop\n") == 0) {
          kill(child_pid, SIGSTOP);
          break;
      }
    }
  }
  return 0;
}
Yunbin Liu
  • 1,484
  • 2
  • 11
  • 20