I have a problem with the WIFSIGNALED()/WTERMSIG() macros, after using waitpid()
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
{
pr开发者_如何学Pythonintf("Can not read the reason for termination\n");
}
}
else /*child*/
{
execvp(argv[1],argv+1);
exit(EXIT_SUCCESS);
}
}
return 1;
}
The WIFSIGNALED()
and WTERMSIG()
macros both expect plain int
s, not pointers to int
s. 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
.
精彩评论