Jack-O-Intern
Jack-O-Intern

Reputation: 1

How to send program to background and stop executing?

I am new to C signal handling. So I am trying to suspend program execution and send it to the background and then continue it later when SIGCONT is sent. Not sure how to suspend the program. If I were to continue the program, it should also be resume where it left off. But I am not sure how to accomplish this. Should I simply use pause()? Any advice would be appreciated, I am simply practicing and playing around with signal handling.

void tSTP_handler(int signal){
    // not sure how to suspend program execution in handler and send it to background
}

int main(){
    signal(SIGTSTP, tSTP_handler);
    while(1){
         printf("Not suspended\n");
    }
    printf("resumed\n");
}

Upvotes: 0

Views: 637

Answers (1)

ccxxshow
ccxxshow

Reputation: 914

simple steps:

  1. run a process, and fork a child process, print a log every 1ms on the child process
  2. send a signal (SIGSTOP, SIGCONT) to the child process on the parent process, paused for 100ms between SIGSTOP and SIGCONT
  3. observe the delay of the child process.

code:

#include <stdio.h>
#include <signal.h>
#include <sys/time.h>
#include <sys/wait.h>
#include <unistd.h>

#define MS 1000 // 1ms

long get_curr_time()
{
    struct timeval tv;
    gettimeofday(&tv, NULL);
    return tv.tv_sec * 1000000L + tv.tv_usec;
}

void do_child()
{
    int i = 0;
    long start, end, cost;
    for(i = 0; i < 3; i++) {
        start = get_curr_time();
        usleep(MS);
        end = get_curr_time();
        cost = end - start;
        if (cost > 2 * MS)
            printf("%d. cost time: %ld us, Delayed by SIGSTOP.\n", i, cost);
        else
            printf("%d. cost time: %ld us\n", i, cost);
    }
}

int main()
{
    int pid;
    pid = fork();
    if (pid == 0) {
        do_child();
    } else {
        usleep(2 * MS);

        kill(pid, SIGSTOP);     // pause 100ms
        usleep(100 * MS);
        kill(pid, SIGCONT);

        waitpid(pid, NULL, 0);
    }
    return 0;
}

result:

0. cost time: 1066 us
1. cost time: 100886 us, Delayed by SIGSTOP.
2. cost time: 1057 us

Upvotes: 1

Related Questions