[英]control xterm using pseudo terminal in C
我開始使用套接字編寫一個簡單的聊天應用程序(Linux)
。 我想啟動一個單獨的終端(xterm)
進行聊天。 所以我試圖從聊天應用程序中 fork 並執行一個 xterm。 但是我無法使用我的聊天應用程序控制新執行的 xterm 窗口。 我使用了dup2(slave, STDIN_FILENO)
、 STDOUT_FILENO
和STDERR_FILENO
,但是,新的 xterm 窗口仍然沒有使用“從”終端進行 I/O。
(我嘗試了https://www.linusakesson.net/programming/tty/ 、 https://rkoucha.fr/tech_corner/pty_pdip.html和“Unix環境中的高級編程”中的代碼)
我也試過 xterm -S 選項。 它正在工作,但我不滿意使用它。
這是我如何做類似的事情(在 Linux 下的 C 中):
// Open a pseudo-terminal master
int ptmx = open("/dev/ptmx", O_RDWR | O_NOCTTY);
if (ptmx == -1) {
printf("Failed to open pseudo-terminal master-slave for use with xterm. Aborting...");
quit(); // closes any open streams and exits the program
} else if (unlockpt(ptmx) != 0) {
printf("Failed to unlock pseudo-terminal master-slave for use with xterm (errno. %d). Aborting...", errno);
close(ptmx);
quit();
}
else if (grantpt(ptmx) != 0) {
printf("Failed to grant access rights to pseudo-terminal master-slave for use with xterm (errno. %d). Aborting...", errno);
close(ptmx);
quit();
}
// open the corresponding pseudo-terminal slave (that's us)
char *pts_name = ptsname(ptmx);
printf("Slave-master terminal: %s", pts_name);
int pts = open(pts_name, O_RDWR | O_NOCTTY);
// launch an xterm that uses the pseudo-terminal master we have opened
char *xterm_cmd;
asprintf(&xterm_cmd, "xterm -S%s/%d", pts_name, ptmx);
FILE *xterm_stdout = popen(xterm_cmd, "r");
if (xterm_stdout <= 0) {
printf("Failed to open xterm process. Aborting...");
ptmx = 0;
close(ptmx);
quit();
}
// Set the stdin / stdout to be the pseudo-terminal slave
dup2(pts, STDIN_FILENO);
dup2(pts, STDOUT_FILENO);
printf("This appears in the terminal window.\n");
現在,在終端中輸入的任何內容都會被饋送到程序的stdin
,而程序輸出到stdout
任何內容都會出現在終端中。 您可以隨意使用readline
庫、 linenoise
甚至curses
。
您可以使用-e
選項將命令直接傳遞給 xterm。 您可以在單獨的二進制文件中創建聊天本身(讀取標准輸入並寫入標准輸出等),而 xterm 只需要執行該二進制文件。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.