我正在实现一个家庭作业终端。
我快完成了,我只需要实现一个 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)停止子级后)父级不会从停止的地方继续(等待进程)。我不知道信号处理方法完成后它会继续到哪里。
如果我在信号处理方法中调用 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
调用应在其等待的进程停止时返回。
关于C++、linux、fork、execvp、waitpid 和 SIGTSP,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13485462/