c - 如何使用termios将控制权返回到C中的终端
问题描述
我正在创建一个 shell,它将模仿 Linux 中 shell 的行为,比如执行ls、mkdir、find等命令,现在我使用termios来监听箭头键和Enter键的按下,如果用户按下了然后箭头键向用户显示之前执行的命令。但是在执行我的shell程序之后,在输入第一个命令之后,例如:ls
命令的输出将被显示,但之后我无法执行另一个命令,因为在终端中输入并按 Enter 只是在新行上打印文本并且不会不要执行它。
我的代码:
#include <stdio.h>
#include <stdlib.h>
#include <termios.h>
#include <term.h>
#include <curses.h>
#include <unistd.h>
static struct termios initial_settings, new_settings;
static int peek_character = -1;
void init_keyboard();
void close_keyboard();
int kbhit();
int readch();
int main() {
int ch;
char str[1000][200];
init_keyboard();
int i = 0;
int j = 0;
while(ch != 'q') {
if(kbhit()) {
ch = readch();
if (ch == 10) {
system(str[i]);
i++;
} else {
str[i][j] = ch;
j++;
}
}
}
close_keyboard();
exit(0);
}
void init_keyboard() {
tcgetattr(0, &initial_settings);
new_settings = initial_settings;
// new_settings.c_iflag &= ~BRKINT;
// new_settings.c_iflag &= ICRNL;
new_settings.c_lflag &= ~ICANON;
new_settings.c_lflag &= ECHO;
new_settings.c_lflag &= ~ISIG;
new_settings.c_cc[VMIN] = 1;
new_settings.c_cc[VMIN] = 0;
tcsetattr(0, TCSANOW, &new_settings);
}
void close_keyboard() {
tcsetattr(0, TCSANOW, &initial_settings);
}
int kbhit() {
char ch;
int nread;
if (peek_character != -1) {
return 1;
}
new_settings.c_cc[VMIN] = 0;
tcsetattr(0, TCSANOW, &new_settings);
nread = read(0, &ch,1);
new_settings.c_cc[VMIN]=1;
tcsetattr(0, TCSANOW, &new_settings);
if (nread == 1) {
peek_character = ch;
return 1;
}
return 0;
}
int readch() {
char ch;
if (peek_character != -1) {
ch = peek_character;
peek_character = -1;
return ch;
}
read(0, &ch,1);
return ch;
}
解决方案
你需要 fork() 来创建新进程,因为 system() 执行你的命令并离开......试试这个代码:
int main() {
int ch;
char str[1000][200];
init_keyboard();
int i = 0;
int j = 0;
pid_t father;
father = 0;
while(ch != 'q') {
if(kbhit()) {
ch = readch();
father = fork();
if (father == 0)
{
if (ch == 10) {
system(str[i]);
i++;
} else {
str[i][j] = ch;
j++;
}
}
}
}
推荐阅读
- symfony - symfony 4 中的 Vue.js
- c++ - LLVM - 类型替换创建重复类型
- python - Python:我的代码创建了多个列表
- python - isalpha() if 语句被忽略 python
- javascript - 追加数据时出现 Jquery XSS 问题
- javascript - 数据正在插入对象中,但未在反应中更新列表组
- spring - JOOQ中的GroupBy时间戳间隔
- python - QtDesigner在保存到ui文件时重新排序单选按钮
- git - GIT,不要合并特定文件
- javascript - Sequelize 类方法适用于一个模型,但不适用于另一个模型