程序运行时如何获取用户输入的字符串? 当用户在终端输入“stop”时,我想中断 while 循环。 然而,scanf 或 gets 只是等待输入。
这只是我想要的一个例子。
#include <stdio.h>
int main() {
int i=0;
while (1) {
//if ( userinput == "stop") break;
printf("printing..%d\n",i++);
}
return 0;
}
最佳答案
可以使用fork()
和kill()
、子进程句柄printf()
、父进程句柄来实现userinput
,当用户输入stop
时,父进程kill
子进程。
以下代码
可以工作:
#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;
}
关于c - 当程序运行时,如何通过终端获取用户输入?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53655110/