在ctrl+C和ctrl+z上的C++SIGINT和SIGSTP

C++ SIGINT and SIGSTP over ctrl+c and ctrl+z

本文关键字:C++SIGINT SIGSTP 上的 ctrl+z ctrl+C      更新时间:2023-10-16

我在一个shell上写东西,想要实现信号SIGSTPSIGINT。当用户启动一个新进程并按下CTRL+C时,它应该向该进程发送一个SIGINT,当按下CTRL+Z

这是我到目前为止的代码:

string inputNew = input;
vector<char*> arguments;
size_t lastChar = 0;
for(int i = 0; i < input.size(); i++)
{
    char& c = input[i];
    if((c == ' ' || c == 't'||c == 'n') && lastChar != i)
    {
        c = ''; 
        arguments.push_back(&input[0] + lastChar);
        lastChar = i+1;
    }
}
bool checkIfBackground(string & input)
{
    size_t lastChar = input.size() - 1;
    if(input[lastChar] == '&')
    {
        return true;
    }
    return false;
}
if((pid = fork()) < 0) {
    exit(1);
} else if(pid == 0) {
    execvp(arguments[0], &arguments[0]);
    exit(1);
} else if(checkIfBackground(inputNew) == false) {
    int status;
    pid_t pid_r;
    if(waitpid(pid, &status, 0) < 0) {
        cout << "PID not known!";
    }
} else {
    cout << "Prozess is waiting in the background." << endl;
}

我不知道如何在代码中实现SIGSTP和SIGINT信号。

请参阅sigaction(2)手册页面。它解释了如何设置实现一个信号处理程序。

请注意,信号处理程序是异步的。这有许多含义。阅读手册页面,花点时间在谷歌上。