sigtstp信号不阻止孩子
SIGTSTP signal not stopping child?
我正在尝试编写一个程序,该程序叉,孩子执行命令,然后将控制返回给父母。我很难将SigTSTP(C-Z)信号按预期工作,但是...我希望父母忽略它,但是孩子会停下来并将控制权返回父母,以便以后可以恢复或杀死孩子(带有内置命令)。我将相关的代码隔离到一个较小的程序中只是为了测试它,似乎a)当C-Z键入C-Z时,孩子不会停止,b)它确实停止了,但不会返回到父母的控制权(我是我倾向于这一点,因为当我将CAT用于Stdin时,它在C-Z之后的行为不同。这是我的代码。
#include <stdio.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <fcntl.h>
#include <cstring>
#include <unistd.h>
#include <cstdlib>
#include <iostream>
#include <vector>
#include <string>
#include <signal.h>
int main(){
std::cout.setf(std::ios::unitbuf);
std::vector<std::string> vec; vec.push_back("cat");
std::vector<char*> chvec;
for(unsigned int i = 0; i < vec.size(); i++){
chvec.push_back(&vec[i][0]);
}
chvec.push_back(NULL);
vec.erase(vec.begin(), vec.begin() + chvec.size());
char** argv = &chvec[0];
signal(SIGTSTP,SIG_IGN);
pid_t pid;
if((pid = fork()) == 0){
signal(SIGTSTP,SIG_DFL);
/*pid = getpid();
setpgid(pid,pid);*/
std::cout << "before exec" << std::endl;
execvp(argv[0],argv);
perror("exec");
}
else{
//setpgid(pid,pid);
int status;
waitpid(pid,&status,0);
if(WIFEXITED(status) || WIFSIGNALED(status)){
std::cout << "exited or signaled" << std::endl;
}
if(WIFSTOPPED(status)){
std::cout << "process stopped" << std::endl;
}
//std::cout << "process exited" << std::endl;
pause();
}
return EXIT_SUCCESS;
}
在评论中已经指出,您需要修复由于vec
向量被擦除而导致的未定义行为。那是第一个问题。
我看到您的代码正在使用WIFSTOPPED
检查过程的退出状态。
让我们回顾一下wait(2)
系统调用的文档,看看它对此事说什么:
WIFSTOPPED(wstatus) returns true if the child process was stopped by delivery of a signal; this is possible only if the call was done using WUN‐ TRACED or when the child is being traced (see ptrace(2)).
so,在固定了前面提到的未定义行为之后,将您的 waitpid()
调用到:
waitpid(pid,&status,WUNTRACED);
然后,我能够将kill -TSTP <pid>
消息发送到产卵的cat
进程,并获得预期
过程停止
来自测试程序的消息。
P.S。通过依靠孩子的过程,我可以看到孩子的过程正在接收TSTP
信号,并且停止良好。问题简直就是父母没有处理它,没有waitpid()
所需的选项。
相关文章:
- Qt VTK交互风格的信号到小部件
- 获取日期异步信号安全吗?如果在信号处理程序中使用,它会导致死锁吗
- 如何将点击的信号和插槽添加到qt中的自定义按钮中
- 如何在没有信号的情况下从C++执行QML插槽
- 线程之间的布尔停止信号
- 如何在信号处理程序和普通函数中对全局变量进行互斥读写操作
- 当用户在qtablewidget中输入单元格时,如何获得信号?C++
- 有可能在信号处理程序中设置promise吗
- 代码在我的计算机上运行良好,但是在将其提交给coursera时遇到未知的信号11问题
- 在条件变量中触发错误信号的频率是多少
- 更改"child's parent's style sheet"时如何将孩子的样式表重置为 Qt 默认样式表?
- 在信号处理程序中捕获C++未处理的异常并恢复应用程序
- 调试和自由执行中的信号处理
- 升压信号2将插槽传递到成员功能以断开连接
- C++函数包装器来捕获某些信号
- 如何在qt中将信号和插槽与另一个对象连接 --解决了
- 中止信号来自 C++ 中的中止(3) (SIGABRT)
- 如何从父级C 发送给孩子的唤醒信号
- sigtstp信号不阻止孩子
- 如何接收来自孩子的信号