How to make readLine() timeout

蓝咒 提交于 2021-01-19 08:04:11

问题


My application basically is a CLI with all the expected features like prompt, history etc., it needs to wait on STDIN for user input. For this I am using readLine system call. I have a created a network socket which is used to send the message read from user to server. My application is single threaded one. Because my application is blocked for user input, the socket created is not responding to keep-alive messages from server. I want to know if there is a way make readLine timeout after some time, so that I will just poll on my network socket and come back to wait on readLine?.

I know there is one solution where I can spawn a thread to take care of network operations. But I dont want to make my app multithreaded.


回答1:


I am using readLine system call.

libreadline

You provide inconsistent information. What system would that be that has a system call readLine?
If you use libreadline, you are rather calling library functions. But then, according to the GNU Readline Library Function and Variable Index, there is no function readLine, there's only readline. With it you could use either the

  • Variable: rl_hook_func_t * rl_event_hook
    If non-zero, this is the address of a function to call periodically when Readline is waiting for terminal input. By default, this will be called at most ten times a second if there is no keyboard input.

    (you'd set it to a function where you poll your network socket and respond to messages)

or the

  • Alternate Interface
    An alternate interface is available to plain readline(). Some applications need to interleave keyboard I/O with file, device, or window system I/O, typically by using a main loop to select() on various file descriptors. To accommodate this need, readline can also be invoked as a `callback' function from an event loop. There are functions available to make this easy.

    There's an example program using the alternate interface: Alternate Interface Example.




回答2:


how about using this? I also tried to find the same solution as this thread. and those code just works but I'm not sure it has no prob. if anybody found fault in it or better solution, please let me know it.

int event_hook(){
    rl_line_buffer[0] = '\0';
    rl_done = 1;
    return 0;
}

rl_event_hook = event_hook;
rl_set_keyboard_input_timeout(500000);  // in usec
char* line = readline(">");      // returns after 1s. I don't know why it takes double time that I set up.


来源:https://stackoverflow.com/questions/31181148/how-to-make-readline-timeout

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!