简体   繁体   中英

How to output in multiple terminal windows with a c program

I am writing a simple chat-room application in c using posix sockets. However I'll have this issue in sending messages.

(client1)say something: Hello folks! what are 

client2 said: xyzabc

client3 said: dsgh

Here above is the client1's terminal window where he was trying to send "Hello folks! what are you doing?" but before he could write his messsage and press enter , client2 and client3 sent something.(separate thread for receiving messages)

I'm trying to tackle this issue by using 2 different terminal windows for each client, one for writing the message and another for displaying the chat messages.

To begin with I've opened a gnome-terminal window by writing

system("gnome-terminal");

but now,

I want to perform some read write operations on the terminal window I've opened and the existing window.

printf("This is existing window"); //want to print this on existing terminal

printf("this is new terminal window"); //want to print this on new terminal

scanf("%d",&a); //take input from existing window

scanf("%d",&b); //take input from new window

I've read here that I can do it by reading/writing from proper /dev/pts/<n> file. But how do I find the n in the /dev/pts/<n> for the current terminal and the new terminal window I just opened? Is there any better way of solving the issue?

One known good way is using the alternate interface to GNU 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 accomodate this need, readline can also be invoked as a `callback' function from an event loop.

The pseudocode skeleton is as follows:

  rl_callback_handler_install (prompt, my_handler)

  while true
     wait on stdin and socket (select or poll)
     if stdin is ready            
        rl_callback_read_char();
     if socket is ready
        read message from socket
        save readline state
        print message
        restore readline state

   void my_handler(char* line)            
        send line to socket

Saving and restoring readline state is

  saved_line = rl_copy_text(0, rl_end);
  rl_save_prompt();
  rl_replace_line("", 0);
  rl_redisplay();

  rl_restore_prompt();
  rl_replace_line(saved_line, 0);
  rl_point = saved_point;
  rl_redisplay();
  free(saved_line);

A complete, if rudimentary, chat program that utilises this method can bee found here .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM