繁体   English   中英

如何使用AC程序在多个终端窗口中输出

[英]How to output in multiple terminal windows with a c program

我正在使用posix套接字在C中编写一个简单的聊天室应用程序。 但是,在发送消息时会遇到这个问题。

(client1)say something: Hello folks! what are 

client2 said: xyzabc

client3 said: dsgh

上面是client1的终端窗口,他试图在该窗口中发送“ Hello们!您在做什么?” 但是在他写出信息并按回车键之前,client2和client3发送了一些消息。(用于接收消息的单独线程)

我试图通过为每个客户端使用2个不同的终端窗口来解决此问题,一个用于编写消息,另一个用于显示聊天消息。

首先,我通过编写打开gnome-terminal窗口

system("gnome-terminal");

但现在,

我想在打开的终端窗口和现有窗口上执行一些读写操作。

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

我在这里阅读可以通过从正确的/dev/pts/<n>文件中进行读取/写入来实现的目的。 但是,如何在/dev/pts/<n>找到当前终端和刚打开的新终端窗口中的/dev/pts/<n> 有解决这个问题的更好方法吗?

一种已知的好方法是使用GNU Readline的备用接口

某些应用程序通常需要通过使用主循环在各种文件描述符上使用select()来使键盘I / O与文件,设备或窗口系统I / O交织。 为了适应这种需求,还可以从事件循环中将readline作为“回调”函数来调用。

伪代码框架如下:

  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

保存和还原readline状态为

  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);

可以在此处找到使用此方法的完整的,基本的聊天程序。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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