Home > Net >  How to resume a stopped process?
How to resume a stopped process?

Time:09-30

Following this documentation, I am testing how to stop and resume a process. I have a basic code to test as follows:

#include <iostream>
#include <csignal>
#include <unistd.h>

int main() {
    std::cout << "Hello" << std::endl;
    int pid = getpid();
    kill(pid, SIGSTOP);
    kill(pid, SIGCONT);
    std::cout << "Bye" << std::endl;
    return 0;
}

The output is:

Hello

It stops the process but never resumes it. How should I fix it?

Thank you.

CodePudding user response:

A solution, if a bit complicated, is to create a child process to start and stop the parent. Here is a small code example, that might help:

#include <iostream>
#include <csignal>
#include <sys/types.h>
#include <unistd.h>

int pid; //Include declaration outside so it transfers to the child process

int main() {
    std::cout << "Hello" << std::endl;
    pid = getpid();
    int returned_pid = fork(); //Duplicate process into 2 identical processes
    if(returned_pid) {
        // If it is the parent process, then fork returns the child process pid
        // This is executed by the parent process
        usleep(1000); // Sleep a millisecond to allow for the stop command to run
    } else {
        // If fork returns 0, then it is the child process
        // The else is executed by the child process
        kill(pid, SIGSTOP); // Stop parent process
        usleep(3000000);    // Delay 3 seconds
        kill(pid, SIGCONT); // Resume parent process
    }
    if(returned_pid) { // Only print if parent process
        std::cout << "Bye" << std::endl;
    }
    return 0;
}

Clarification: The fork command returns 2 different values in the 2 processes: 0 in the child, and the pid of the child process in the parent.

Other note: When running this in a terminal, it will look weird, as the terminal may note that the process was stopped and give a new command line, but then the process resumes, so prints Bye over it. Just a note.

CodePudding user response:

You can use sleep function to stop and resume the process.

//add windows.h header file 
sleep(10);//sleep(x) x is number of seconds 
//process will pause for 10 seconds and will resume after that
  • Related