如何从 C 中的 stdin 进行非阻塞输入 [英] How to do nonblocking input from stdin in C
本文介绍了如何从 C 中的 stdin 进行非阻塞输入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有以下情况我有一个程序连续对文件进行一组操作,我想在按下特定键时停止并执行另一组操作.
I have follow situation I have an program make an set of operations on a file continuously and I want, when a specific key is pressed, to stop and do another set of operations.
为此,我尝试使用带有
For this I tryed use scanf
of an character with
fcntl(0, F_SETFL, O_NONBLOCK);
和
while(feof(stdin))
但它没有按预期工作.
我已经搜索过,有些地方有人说要使用 select
,但我找不到如何使用它.
I have searched and in some places someone says to use select
but I can't find how to use it.
有人可以以某种方式给我建议吗?
Anyone can advice me somehow?
我提供更多信息的主要功能:
my main function to provide more information:
int main(int argc, char *argv[])
{
if(argc>1){
char* password;
char* password2;
printf("Password? ");
password = get_password();
printf("Repita a password? ");
password2 = get_password();
if(strcmp(password,password2)!=0){
printf("Passwords diferentes!\n");
exit(1);
}
FILE *fptr;
fptr = fopen("./regist", "r");
if(fptr == NULL) //if file does not exist, create it
{
fptr = fopen("./regist", "w");
}
fclose(fptr);
if(find_username(argv[1])){
printf("Utilizador ja existe\n");
exit(1);
}
add_user_regist(argv[1],password);
printf("Utilizador %s adicionado.\n",argv[1]);
exit(0);
}
char readbuf[250];
/* Create the FIFO if it does not exist */
umask(0);
mknod(FIFO_FILE, S_IFIFO|0666, 0);
printf("Servidor iniciado.\nEm modo de espera de mensagens\n");
fcntl(0, F_SETFL, O_NONBLOCK);
while(1){
char c = getchar();
if(c=='q' || c=='Q')
exit(0);//by now only goes out
fp = fopen(FIFO_FILE, "r");
fgets(readbuf, 250, fp);
fclose(fp);
if(readbuf[0]=='U')
user_access(readbuf);
else if(readbuf[0]=='W')
who_online(readbuf);
else if(readbuf[0]=='R'){
char* tmp;
strtok(readbuf,":");
tmp = strtok(NULL,";");
remove_online(tmp);
printf("# %s fez logout\n",tmp);
}
else if(readbuf[0]=='F'){
process_msg(readbuf);
}
}
return(0);
}
推荐答案
使用 GNU 阅读线:
#include <readline/readline.h>
#include <stdio.h>
static int func(int count, int key)
{
printf ("key pressed: %c\n", key); /* exec your function */
return 0;
}
int main(void)
{
char *line;
rl_bind_key('x', func); /* 'x' is the specific key */
line = readline ("> ");
printf("%s\n", line);
return 0;
}
使用-lreadline
这篇关于如何从 C 中的 stdin 进行非阻塞输入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文