簡體   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