2012-11-21 69 views
2

我正在实现家庭作业终端。
我差不多完成了,我只需要实现一个bg(Background)和一个fg(Foreground)命令。
我的代码看起来是这样的:C++,linux,fork,execvp,waitpid和SIGTSP

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()它会起作用,但我不想递归。我猜,我会很快得到一个计算器...

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

void sigtstp_handel(int signal){ 

    if(is_foreground_process_alive()) 
     kill(foreground_process_pid, SIGTSTP); 

    // run(); 
} 

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

谢谢!

回答

2

阅读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调用应该返回。

+0

非常感谢!有效! – m1o2