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;
}
4
  • 1
    You can start another thread that will watch the terminal. Commented Dec 6, 2018 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. Commented Dec 6, 2018 at 15:56
  • @DYZ Thanks, how can it watch the terminal? Commented Dec 6, 2018 at 16:03
  • 2
    Possible duplicate of C non-blocking keyboard input Commented Dec 6, 2018 at 16:13

1 Answer 1

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;
}
Sign up to request clarification or add additional context in comments.

1 Comment

It works and exactly what I wanted Thank you very much :>

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.