2012-11-21 78 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