gpt4 book ai didi

c - shell 实现 : signal handling: Any way to return early from wait()?

转载 作者:太空狗 更新时间:2023-10-29 11:22:22 24 4
gpt4 key购买 nike

我正在为我的操作系统类做一个 shell 项目,我们已经完成了信号处理部分。作业要求我们捕获 SIGINTSIGTSTP 并将信号发送到子进程。这是我到目前为止所得到的。如果你遇到 undefined variable 或函数,希望你能根据标识符理解它的含义:

char input[ MAX_INPUT ];

sigset_t sig;
pid_t *suspendedChildren = NULL;
int nSuspendedChildren = 0;
pid_t currentChild = 0;

int main( int argc, char *argv[] )
{
char quit = 0;

setup();

do
{
getInput();
quit = handleInput( input );
} while( quit != EXIT_NUMBER );

return 0;
}

void setup( void )
{
// block the interrupt signal
sigaddset( &sig, SIGINT);
sigprocmask( SIG_BLOCK, &sig, NULL);

// handle the suspend signal
signal( SIGTSTP, suspendChild );
}

void suspendChild( int signal )
{
if (currentChild) // meaning that there is a child process currently running
{
// increment suspended children counter
nSuspendedChildren++;

// reallocate the array of suspended children
suspendedChildren = (pid_t *)realloc( suspendedChildren, nSuspendedChildren*sizeof(pid_t));
suspendedChildren[nSuspendedChildren-1] = currentChild;

// send suspend signal to child
kill( currentChild, SIGTSTP );

printf( "\n[%d]+ Stopped\t\t", nSuspendedChildren );
puts( input );
putchar( '\n' );

// set the global to 0
currentChild = 0;

main( 0, NULL );
}
}

int handleInput( char *s )
{
// string tokenizing / parsing...
// checks for redirection / background process requests
// (not relevant to question being asked so omitted)

currentChild = fork();
if (currentChild) // parent process
{
wait( &status );
}
else // child process
{
execvp( prgm, tokens );
}
}

因此,为了处理 SIGINT,我简单地阻止了信号,以便子进程(执行的命令)接收它,而父进程(shell)忽略它。这工作得很好,但它是 SIGTSTP 并且暂停了我遇到问题的进程。对于这个信号,我选择在它到达时调用一个信号处理程序。这非常有效,因为我相信进程的默认 SIGTSTP 处理行为是挂起,但由于我的 shell 正在等待(请参阅 wait(&status))子进程返回(目前已暂停),我的整个终端都处于僵尸状态。我无法按 ctrl+D 退出,我只需要关闭窗口并重新登录...

所以重申这篇文章的标题,有什么方法可以从信号处理程序的 wait(int*) 提前返回?我查阅了文档并发现了这个声明:

wait also returns if a signal is received and is not ignored.

但是,仅此而已,并没有提供进一步的见解。

最佳答案

而不是 wait 考虑它是否真的是您真正想要使用的 waitpid(带有特定选项)。 – 鸭子

关于c - shell 实现 : signal handling: Any way to return early from wait()?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20353407/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com