I'm writing a chat client which has to take in user input while simultaneously outputting received messages.
So far I've forked into two separate processes, one of which goes on to listen to the socket connection and write out the received strings with printf. The other uses readline to read user input and send it to the server.
The problem I have now is that printed strings show up on top of my input string in the terminal.
I thought the following code would prevent this, but it looks like it isn't sharing across threads or something.
#define xprintf(...) my_rl_printf(__VA_ARGS__)
void my_rl_printf(char *fmt, ...)
{
int need_hack = (rl_readline_state & RL_STATE_READCMD) > 0;
char *saved_line;
int saved_point;
if (need_hack)
{
saved_point = rl_point;
saved_line = rl_copy_text(0, rl_end);
rl_save_prompt();
rl_replace_line("", 0);
rl_redisplay();
}
va_list args;
va_start(args, fmt);
vprintf(fmt, args);
va_end(args);
if (need_hack)
{
rl_restore_prompt();
rl_replace_line(saved_line, 0);
rl_point = saved_point;
rl_redisplay();
free(saved_line);
}
}
In my little test harness
if (fork() == 0)
{//child
int time = 0;
int count = 0;
while(1)
{
ftime(&tp);
if (tp.time > time)
{
time = tp.time;
xprintf("count %d\n",count++);
}
}
}
else
{
int time = 0;
while(1)
{
usr_in = readline("");
xprintf("%s\n",usr_in);
}
}