gpt4 book ai didi

c - 安装 SIGTSTP 前台进程

转载 作者:行者123 更新时间:2023-12-04 05:52:59 26 4
gpt4 key购买 nike

我正在尝试为正在运行的前台进程安装 CTRL-Z (SIGTSTP) 处理程序。

我在 sigaction 之前设置了处理程序 ( wait )在父级。这是正确的地方吗?好像不太行。。

编辑:

我正在写一个shell。这是我的代码外观的概述。我目前在父级中设置处理程序,如下所示(这似乎不起作用)。

// input from user for command to run
pid_t pid;
pid = fork();

// Child Process
if (pid == 0) {
// handle child stuff here
// exec() etc...
}

else if (pid < 0)
// error stuff

/* Parent Here */
else {
// Give process terminal access
// SET HANDLER FOR SIGTSTP HERE???
wait()
// Restore terminal access
}

最佳答案

你做的事情完全错误。

您不要将 SIGTSTP 发送到子进程,tty 直接将 SIGTSTP 发送到子进程。

尝试

$ stty -a
speed 38400 baud; rows 55; columns 204; line = 0;
intr = ^C; quit = ^\; erase = ^?; kill = ^U; eof = ^D; eol = <undef>; eol2 = <undef>; swtch = <undef>; start = ^Q; stop = ^S; susp = ^Z; rprnt = ^R; werase = ^W; lnext = ^V; flush = ^O; min = 1; time = 0;
-parenb -parodd cs8 -hupcl -cstopb cread -clocal -crtscts
-ignbrk -brkint -ignpar -parmrk -inpck -istrip -inlcr -igncr icrnl ixon -ixoff -iuclc -ixany -imaxbel -iutf8
opost -olcuc -ocrnl onlcr -onocr -onlret -ofill -ofdel nl0 cr0 tab0 bs0 vt0 ff0
isig icanon iexten echo echoe echok -echonl -noflsh -xcase -tostop -echoprt echoctl echoke

注意:
susp = ^Z;

告诉 tty 如何处理“CTRL-Z”,当 tty 得到 ^Z 时,它会发送 SIGTSTP 信号到 当前前台进程组中的所有进程

如何处理进程组

当你在 shell 中启动一个新进程时,在 execvX 之前,将新进程放入新进程组,然后调用 tcsetpgrp设置新的进程组前景。所以任何 future 的信号都会直接发送到子进程。如果子进程 fork 新进程,他们将在同一个进程组中;所以当按下 ^Z 时,整个进程组将被挂起。
pid = fork()
if (pid) {
// parent
setpgid(pid, pid); // put child into a new process group
int status;
wait(pid, &status, 0);
} else {
// child
pid = getpid();
setpgid(pid, pid);
if (isatty(0)) tcsetpgrp(0, pid);
if (isatty(1)) tcsetpgrp(1, pid);
if (isatty(2)) tcsetpgrp(2, pid);
execvX ...
}

一旦来自 tty 的任何信号导致子进程停止/终止/退出,您的 shell 将从 wait 返回。 ,检查状态以了解 child 发生了什么。

防止你的 shell 停止

你的 shell 应该屏蔽 SIGTSTP 信号,因为 shell 不会挂起。您在开始时执行此操作,当您启动 shell 时。但是不要忘记fork会派生sigmask,所以你需要在子进程fork之后启用SIGTSTP。

关于c - 安装 SIGTSTP 前台进程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9853921/

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