【问题标题】:Ubuntu C How to stop child process using SIGTSTP then resume it using SIGCONT?Ubuntu C 如何使用 SIGTSTP 停止子进程,然后使用 SIGCONT 恢复它?
【发布时间】:2020-06-26 05:36:34
【问题描述】:
#include <signal.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <unistd.h>


int pid = 0;

// some very time-consuming function
void childLabor() {
    for (long long i=1;i<=10000000000;i++) {
        //printf("i'm printing\n");
        fflush(stdout);
    }
}

// stop the process who calls this
void stopYourself() {
    // TODO
}

void childReceiveStop() {
    signal(SIGTSTP, childReceiveStop);
    printf("I have important things to do first before stopping\n");
    fflush(stdout);
    // do important things

    printf("I stop myself now\n");
    fflush(stdout);
    stopYourself();
}

void childReceiveContinue() {
    signal(SIGCONT, childReceiveContinue);
}

int main()
{
    pid = fork();
    if (pid==0) {
        signal(SIGTSTP, childReceiveStop);
        signal(SIGCONT, childReceiveContinue);
        stopYourself();     // wait until parent sends SIGCONT
        childLabor();
    }
    else {
        // start/stop child every 2 second
        kill(pid,SIGCONT);
        for (int i=1; i<=100; i++) {
            printf("sending signal stop\n");
            fflush(stdout);
            kill(pid, SIGTSTP);
            sleep(3);

            printf("sending signal start\n");
            kill(pid, SIGCONT);
            sleep(1);
        }
    }

    return 0;
}

基本上我想在这个例子中做的是让孩子打印 3 秒钟,然后停止它,然后让它再次打印,......当孩子收到 SIGTSTP 时,它应该停止。当它收到 SIGCONT 时,它应该继续。

但是,不管有没有处理程序,当子进程收到 SIGTSTP 信号时,它根本不会停止。

我该如何解决这个问题?谢谢。

【问题讨论】:

    标签: c multithreading process signals fork


    【解决方案1】:

    SIGTSTP 用于从终端向进程发送停止信号。在您的情况下,您需要从父进程发送停止信号。所以你需要SIGSTOP 而不是SIGTSTP。所以用SIGSTOP替换SIGTSTP

    也抓不到SIGSTOP。所以你不需要为SIGSTOP 提供处理程序。

    【讨论】:

    • 如果我希望子进程在被 SIGSTOP-ed 之前做某事怎么办?
    • 不能使用SIGSTOP。也许改用SIGUSR1SIGUSR2
    • 那我如何告诉进程在收到 SIGUSR1 时停止?
    • 例如,收到SIGUSR1 的子进程可以通过条件变量使自己进入睡眠状态,并且可以继续接收信号。
    • 你能解释更多关于“通过条件变量睡眠”的信息吗? while (something==false) { } 不算数,因为这意味着我必须在代码中的每个正常语句之后添加该语句
    猜你喜欢
    • 1970-01-01
    • 2021-09-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多