1

1I am trying kill a child process after 1 second. The child process is an external c program that runs some nested for loops and and prints "ALL DONE" if it makes it through. The loops take about 10 seconds, so if I set up my timer and action handler correctly, it should never make it to "ALL DONE."

The child process is run using execve, after the timer is created.

pid_t pid = -1;

void time_handler(int signal){
    printf("in time_handler\n");
    kill(pid, SIGKILL);
}

int main(int argc, char *argv[]){
    char *const path = "/home/aidan/CSC252/a4/test";
    char *const env_args[] = { (char*)0 };
    pid = fork();

    while(1==1){
        if(pid == 0){ //in child
            printf("in child\n");
            struct sigaction sa;
            struct itimerval *timer = malloc(sizeof(struct itimerval));
            sa.sa_handler = &time_handler;
            printf("sigaction: %d\n", sigaction(SIGVTALRM, &sa, NULL));
            timer->it_value.tv_sec = 0;
            timer->it_interval.tv_sec = 1;
            printf("settimer: %d\n", setitimer(ITIMER_REAL, timer, NULL)); //start timer
            //printf("getitimer: %d\n", getitimer(ITIMER_REAL, timer)); 
            int exec =  execve(path, NULL, env_args);
            printf("Exec is %d\n", exec);   //-1 = error
        }
        else if (pid > 0){//in parent
            printf("in parent, pid: %d\n", pid);
            printf("wait: %d\n", wait(NULL));
            pid = 0;
        }
    }    
}

Both sigaction and setitimer return 0, but I am not sure I am actually handling the timer expiration correctly. I tried reading up on

alarm(5);

but my results were unsuccessful.

current output is:

in parent, pid: 2362
in child
sigaction: 0
settimer: 0
In test
ALL DONE
wait: 2362
in child
sigaction: 0
settimer: 0
In test
ALL DONE

I am not sure why it run only two times and then exits.

  • 1
    Well, the [docs](http://man7.org/linux/man-pages/man2/setitimer.2.html) are specific: `ITIMER_REAL .... At each expiration, a SIGALRM signal is generated.` It's not `SIGVTALRM` – KamilCuk Nov 23 '19 at 19:35
  • Thanks, I see that now, I definitely overlooked that, or read the wrong section. However, my program behaves the same way with SIGALRM. – Aidan Goldfarb Nov 23 '19 at 19:40
  • 1
    You set your timer in the child and then exec a new program... of course the timer isn't going to go off; it no longer exists! – Shawn Nov 23 '19 at 21:02

0 Answers0