使用 waitpid() 后,我的 WIFSIGNALED()/WTERMSIG() 宏出现问题
在此代码中,我从命令行启动一个程序,当它被不同于 SIGTERM(正常结束信号)的信号关闭时,我的代码应该重新启动从命令行传递的初始程序。但事实并非如此,事实上我的代码从未重新启动程序,说它已正确终止。在实践中,我的条件“if(WTERMSIG(status)!=SIGTERM)”效果不好,为什么?????? :'(
这是我的代码:
#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;
}
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;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
WIFSIGNALED()
和WTERMSIG()
宏都需要普通的int
,而不是指向int
的指针。这意味着在您的代码中,其中status
是指向 int 的指针,您需要在调用宏时使用*status
来向它们传递整数值。也就是说:为什么要调用
malloc()
为单个int
分配空间呢?只需使用普通变量,如果需要指向它的指针,则使用&status
。另外,在程序成功完成时,您应该从
main()
返回EXIT_SUCCESS
,而不是1
。The
WIFSIGNALED()
andWTERMSIG()
macros both expect plainint
s, not pointers toint
s. This means that in your code, wherestatus
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 singleint
, anyway? Just use a normal variable, and&status
if you need a pointer to it.Also, you should return
EXIT_SUCCESS
frommain()
on successful completion of your program, not1
.