多进程暂停和恢复程序

时间:2018-01-21 14:28:11

标签: c linux signals resume pause

我说它但我找不到任何我想找的东西。任何人都可以给出一个简单的例子如何暂停一段时间(不是给定时间,如sleep())并继续程序?我试了一下,但它只是暂停,然后我唯一能做的就是在第二次printf之前终止程序:

#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <stdlib.h>
#include <string.h>
#include <fcntl.h>
#include<termios.h>
#include<signal.h>
#include <sys/wait.h>

struct sigaction act;
sigset_t to_start, to_stop;




int main(int argc, char *argv[])
{



  int i=0;
printf("BEFORE SIGSUSPEND");




sigemptyset(&to_stop);
sigsuspend(&to_stop);

printf("AFTER SIGSUSPEND");
fflush(stdout)





    return 0;
}

1 个答案:

答案 0 :(得分:1)

您的子进程应以您要发送的信号开头 阻止。

然后你需要确保:

  1. 信号的传递不会终止进程(=&gt;你需要为它设置一个信号处理程序(一个空的信号处理程序))
  2. 可以传递信号(=&gt; sigsuspend会这样做)
  3. 在代码中:

    #include <stdio.h>
    #include <signal.h>
    #include <unistd.h>
    void handler(int X) { }
    int main(void)
    {
        sigset_t to_stop;
        sigemptyset(&to_stop);
        sigaction(SIGINT /*you'd probably use SIGUSR1 here*/,
          &(struct sigaction){ .sa_handler = handler }, 0);
    
        puts("BEFORE");
        /*SIGINT will now wake up the process without killing it*/
        sigsuspend(&to_stop);
        puts("AFTER");
    }
    

    您应该可以使用Ctrl+C进行尝试。在实际代码中,您可能应该使用SIGUSR1 / SIGUSR1或其中一个实时信号。