如何使用termios将控制权返回给C中的终端

问题描述 投票:0回答:1

我正在创建一个外壳,该外壳将模仿Linux中外壳的行为,例如执行ls,mkdir,find等命令,现在我已经使用termios来监听箭头键和按下Enter键,如果用户按下向上箭头键,则向用户显示先前执行的命令。但是在执行完我的shell程序之后,在输入第一个命令后,例如:ls,将显示命令的输出,但是在那之后,我无法执行另一个命令,因为在终端中键入并按Enter只是在new上打印文本行并且不执行它。

我的代码:

#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;
}

c linux termios
1个回答
0
投票

您需要fork()创建新的流程,导致system()执行您的命令并离开...试试这个代码:

© www.soinside.com 2019 - 2024. All rights reserved.