tags:

views:

25

answers:

1

In this code C i launch a program from the command line and when it is closed from a signal different from SIGTERM (signal for normal end) my code should relaunch the initial program passed from the command line. But it is not so, in fact my code never relaunchs program saying that it is properly terminated.In practice my condition"if(WTERMSIG(status)!=SIGTERM)" works bad, WHY????? :'(

This is my code:

#include <stdlib.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
#include <stdio.h>

int main(int argc, char*argv[])
{   
    pid_t pid;
    int* status=(int*)malloc(sizeof(int));
    int term;
    if(argc<2)
    {
        printf("Error: Too few arguments\n");
        exit(EXIT_FAILURE);
    }

    while(1)
    {
    pid=fork();

    if(pid!=0) /*father*/
    {
        waitpid(pid,status,0);
        //term=WIFSIGNALED(status);
        if(WIFSIGNALED(status))
        {
            if(WTERMSIG(status)!=SIGTERM)
            {
                printf("The program %d ended abnormally:\nRelaunching...\n",pid);
                sleep(1);
            }
            else
            printf("The program %d is properly terminated...\n",pid);
            break;

        }
        else
        {
            printf("Can not read the reason for termination\n");
        }

    }
    else    /*child*/
    {
        execvp(argv[1],argv+1);
        exit(EXIT_SUCCESS);
    }
    }

    return 1;

}
+1  A: 

The WIFSIGNALED() and WTERMSIG() macros both expect plain ints, not pointers to ints. This means that in your code, where status is a pointer to an int, you need to use *status when calling the macros, to pass them the value of the integer.

That said: why are you calling malloc() to allocate room for a single int, anyway? Just use a normal variable, and &status if you need a pointer to it.

Also, you should return EXIT_SUCCESS from main() on successful completion of your program, not 1.

unwind
Problem solved!! THANKS!!!!
Andrea