2

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);
    }
  }
Jean-Bernard Pellerin
  • 12,556
  • 10
  • 57
  • 79

2 Answers2

0

My suggestion is you find a way to make one wait on the other. other that if it was pthread, then a wait and signal would solve this problem

  • The goal is to be able to display the messages as they come in, instead of waiting for the user to be done typing then printing received messages. I assume that's what you mean by using semaphores. – Jean-Bernard Pellerin Nov 07 '11 at 03:46
0

I used pthreads instead of fork. Didn't need a semaphore or mutex.
The threading means it's shared memory as opposed to process splitting where I would have had to explicitly declare it as shared. Thus the readline data is available to both threads and the issue is avoided.

Jean-Bernard Pellerin
  • 12,556
  • 10
  • 57
  • 79