【问题标题】:How to interrupt a process and continue it later?如何中断一个进程并在以后继续它?
【发布时间】:2014-05-13 17:04:01
【问题描述】:

我想尝试自己编写一个小型 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

我只想暂停一个进程,稍后再继续。

谁能给我一个提示?

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

【问题讨论】:

    标签: c linux signals fork


    【解决方案1】:

    如果您在程序中捕获SIGTSTP,它不会被挂起。挂起是它的默认行为,一旦安装了自定义处理程序,它就会消失。还有SIGTSTOP,在所有情况下都不能转,暂停进程。

    【讨论】:

    • 所以你的意思是我必须在signal_stop_handler 中给我的Prozess 打电话kill(pid,SIGSTOP)
    • 我已经尝试过了,但是在发送 kill(last_pid,SIGSTOP) my 进程后仍然挂在 do-while 循环中:/ 也许我遵循了错误的逻辑?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-08-02
    相关资源
    最近更新 更多