[英]How can I get this C program to accept new input without adding it to the old input?
[英]C Socket program - How can I accept user input while updating reading from stdout?
我用C語言編寫了一個irc bot應用程序。它只是將服務器消息寫到屏幕上。 這只是通過從服務器filedescriptor讀取的while循環來完成的。 如何同時接受輸入? 我現在想將其擴展為接受用戶輸入,以便可以將其用作客戶端應用程序。 我是C開發的新手,所以我不確定這是如何實現的。 有人可以給我提供示例或為我提供一些文檔的指導嗎?
我基本上想模仿一個telnet應用程序。 標准輸出已更新,用戶可以在控制台上提供服務器命令。
任何幫助/建議將不勝感激。
編輯
我正在Unix環境中進行開發。
謝謝
如果可以,請避免進行多進程和多線程編程。 那條路導致痛苦。 使用事件驅動的編程。 對於您想要做的事情,事件驅動的編程要容易得多 ,並且執行效果也一樣。 C中進行事件驅動編程(與I / O相關)的兩種主要方法是select
和poll
。
這是使用select的工作示例:
#include <stdio.h>
#include <stdlib.h>
#include <sys/time.h>
#include <sys/types.h>
#include <unistd.h>
#include <errno.h>
int
main(void)
{
fd_set rfds;
struct timeval tv;
int retval, len;
char buf[4096];
while (1) {
/* Watch stdin (fd 0) to see when it has input. */
FD_ZERO(&rfds);
FD_SET(0, &rfds);
/* Wait up to five seconds. */
tv.tv_sec = 5;
tv.tv_usec = 0;
retval = select(1, &rfds, NULL, NULL, &tv);
/* Don't rely on the value of tv now! */
if (retval == -1) {
perror("select()");
exit(EIO);
} else if (retval) {
printf("Data is available now.\n");
} else {
printf("No data within five seconds.\n");
continue;
}
if (FD_ISSET(0, &rfds)) {
len = read(0, buf, 4096);
if (len > 0) {
buf[len] = 0;
printf("Got data on stdin: %s\n", buf);
} else {
// fd closed
perror("read()");
exit(EIO);
}
}
}
}
FD_SET用於創建您要選擇的文件描述符列表(從中獲取事件)。 select成功返回(意味着有事件要處理)后,可以使用FD_ISSET查找導致事件的文件描述符。 在您的情況下,您將擁有一個打開的套接字文件描述符,該描述符將添加到集合中並進行適當處理。
有用的文檔包括以下手冊頁:
man 2 select
man 2 poll
man 3 read
man 3 open
您要同時監視套接字和標准輸入。 如果那是正確的,請在此處查看select()系統調用: http : //beej.us/guide/bgnet/output/html/singlepage/bgnet.html#select
有一點東西叫做多線程。 多線程(在C ++中)完全取決於操作系統或外部庫。
如果使用的是Windows,則可以使用“ Windows.h”中定義的beginthread()和endthread()。
它很容易使用。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.