C ++,linux,fork,execvp,waitpid和SIGTSP [英] C++, linux, fork, execvp, waitpid and SIGTSP

查看:311
本文介绍了C ++,linux,fork,execvp,waitpid和SIGTSP的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在实施一个家庭工作终端。

我差不多完成了,我只需要实现一个bg(Background)和一个fg(Foreground)命令。

我的代码如下:

I'm implementing a Terminal for a Home Work.
I almost finished, I just need to implement a bg ( Background ) and a fg ( Foreground ) commands.
my code looks like this:

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)返回控制到父进程(我的终端)。

If it is a foreground process ( if there wasn't a '&' sign at the end ) then I need to be able to stop the foreground process ( the child ) with ctrl+z ( SIGTSTP ) and then to return the control to the father ( my terminal ) from the point it stopped ( waitpid ).

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

the problem is that after a ctrl+z is pressed, ( and after the parent get the control in the signal handle method and stop the child using kill( child_pid, SIGTSTP ) ) the parent don't continue from where it stopped ( the waitpid ). I don't know where it continue after the signal handling method is finished.

如果我在信号处理方法调用run(),它会工作,但我不想递归。我猜我很快会得到一个StackOverFlow ...

If I call run() at the signal handling method it will work, but I don't want the recursion. I'm guessing I'll get a StackOverFlow very soon...

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

here is the code of the Signal Handling Method:

void sigtstp_handel( int signal ){  

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

    // run();
}  

编辑:我不知道是否重要,使用Linux Ubuntu 12.10。

I don't know if it will matter, but I'm using a Linux Ubuntu 12.10. nevertheless, for the Home Work, I'll need it to work on other systems.

谢谢!

推荐答案

阅读 <$ c的官方POSIX参考资料$ c> waitpid


WUNTRACED

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

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

这篇关于C ++,linux,fork,execvp,waitpid和SIGTSP的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆