如何中断进程并在以后继续?

时间:2014-05-13 17:04:02

标签: c linux signals fork

我想尝试自己编写一个小shell,因为这是学习信号的好方法。 但不知怎的,我有一些问题要暂停一个过程,并在以后继续。

execute_command()应该是有趣的部分,因为在我只分割输入的信息之前。

void execute_command(){

    int status = 0;
    pid_t childprocess= fork();
    int wait_state=0;
    if(arg_list[0] == NULL){
        exit(0);
    }

    if(childprocess  <0 ){
        printf(" Could not create childprocess");
    }else if (childprocess == 0){
        int end_state =execvp(*arg_list,arg_list);

        if(end_state < 0){
            printf("Some kind of Error happens here \n");
        }else if(end_state == 0){
        //  printf("Program exited with %d\n",end_state);
        }
            exit(0);
    }else{
        current_process_id = childprocess;
        register_signals();
                    last_pid = getpid();

                    /*When i have found a '&' */
        if(!background_process){
            do{
                waitpid(childprocess,&status,WUNTRACED);
                if( WIFSTOPPED(status) ) {
                                        // later for conitinuing the suspended process
                    last_pid = childprocess;
                                        kill(last_pid,SIGSTOP); // edited line of code !
                }
            }while( !WIFEXITED(status) && !WIFSIGNALED(status));
        }
    }
}

void register_signals(){
    signal(SIGINT,signal_int_handler);
    signal(SIGTSTP,signal_stop_handler);
}

mysignal.c:

void signal_int_handler(int signum){
    printf("[caught SIGINT]\n");
} 
void signal_kill_handler(int signum){
}

void signal_stop_handler(int signum){
printf("[caught SIGTSTP]\n");
}

当我按下“Ctrl + z”时,signal_action执行并打印来自命令signal_stop_handler的消息。 但该程序仍然在do-while-loop中运行。 也许我误解了一些事情。

我的测试输入是:sleep 50

我只想暂停一个流程,并在以后再继续。

有人能给我一个暗示吗?

编辑:我已编辑代码,取决于答案,但它不起作用

1 个答案:

答案 0 :(得分:0)

如果您在程序中抓住SIGTSTP,则不会被暂停。挂起是它的默认行为,一旦安装了自定义处理程序,它就会消失。还有SIGTSTOP无法转移并在所有情况下暂停该过程。