我正在尝试编写一个程序,该程序叉,孩子执行命令,然后将控制返回给父母。我很难将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()
所需的选项。