C++, linux, fork, execvp, waitpid and SIGTSP

C++, linux, fork, execvp, waitpid and SIGTSP

本文关键字:and SIGTSP waitpid fork linux C++ execvp      更新时间:2023-10-16

我正在为家庭工作实现一个终端
我差不多完成了,我只需要实现bg(背景)和fg(前景)命令
我的代码如下:

void run(){
string command[] = parseMyInput( getInput() );  
int fork_result = fork();
if( -1 == fork_result )
//handle error
else if( 0 == fork_result ){  // child
setpgrp();  // I don't want the children to get the signals
if( -1 == execvp( command[0], makeArgs(command) ) )
//handle error
}
else {  // parent
if( command[ length - 1 ] != "&" ){
int status;
waitpid( fork_result, &status, 0 );
//continue after child is finished
//( need to be here also after a SIGTSTP is raised by ctrl+z )
}
}

如果它是一个前台进程(如果结尾没有"&"符号),那么我需要能够用ctrl+z(SIGTSTP)停止前台进程(子进程),然后从它停止的点(waitpid)将控制返回给父进程(我的终端)。

问题是,在按下ctrl+z之后(并且在父级在信号句柄方法中获得控制并使用kill(child_pid,SIGTSTP)停止子级之后),父级不会从它停止的地方继续(waitpid)。我不知道在信号处理方法完成后,它在哪里继续。

如果我在信号处理方法中调用run(),它会起作用,但我不想要递归。我猜我很快就会得到StackOverFlow。。。

这是信号处理方法的代码:

void sigtstp_handel( int signal ){  
if( is_foreground_process_alive() )
kill( foreground_process_pid, SIGTSTP );
// run();
}  

编辑:我不知道这是否重要,但我使用的是Linux Ubuntu 12.10。不过,对于家庭作业,我需要它在其他系统上工作。

谢谢!

阅读waitpid:的官方POSIX参考

WUNTRACED

The status of any child processes specified by pid that are stopped,
and whose status has not yet been reported since they stopped, shall
also be reported to the requesting process.

因此,如果添加WUNTRACED标志,则当等待的进程停止时,waitpid调用应返回。