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

I use the terminal for work at home.
I'm almost done, I just need to implement the bg (Background) and fg (Foreground) commands.
my code is as follows:

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 ) } } 

If this is a foreground process (if there was no "&" at the end), I will need to stop the foreground process (child) using ctrl + z (SIGTSTP), and then return the control to my father (my terminal) from the moment it stops (waitpid).

the problem is that after pressing ctrl + z (and after the parent receives the control in the signal descriptor method and stops it with kill (child_pid, SIGTSTP)), the parent will not continue from where it left off (waitpid). I do not know where it continues after signal processing is complete.

If I call run () in the signal processing method, it will work, but I do not want recursion. I guess I will get StackOverFlow soon ...

here is the code of the signal processing method:

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

EDIT: I don't know if this will make a difference, but I'm using Linux Ubuntu 12.10. however, for Homework I will need this to work with other systems.

Thanks!

+2
source share
1 answer

Reading the official POSIX link for waitpid :

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. 

So, if you add the WUNTRACED flag, the waitpid call should return when the process it is waiting for is stopped.

+2
source

All Articles