工作中,需要使用tftp等协议下载一些文件,但这时候遇到一个问题就是当tftp的服务器没有打开时,system函数会阻塞较长时间(长达数秒),这时候首先想到的就是设置tftp的超时参数,但因为还有很多协议也有超时返回的需求,我就想一劳永逸的封装一个函数来完成这项任务.最后决定重写一下system并设置超时参数,封装的函数如下(system_timeout).这里需要解释进行两层封装的原因:在system_timeout中我们将_system_timeout进行了一层封装,并将信号SIGCHLD设置为SIG_DFL是因为我们在_system_timeout中调用了waitpid,而这个函数在SIGCHLD被忽略是会产生ECHILD错误,手册解释如下:
ERRORS
ECHILD (for waitpid() or waitid()) The process specified by pid (wait-
pid()) or idtype and id (waitid()) does not exist or is not a
child of the calling process. (This can happen for one’s own
child if the action for SIGCHLD is set to SIG_IGN. See also the
Linux Notes section about threads.)
#include <sys/wait.h>
#include <errno.h>
#include <signal.h>
#include <unistd.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int _system_timeout(const char *cmdstring, int timeout);
int system_timeout(const char *cmdstring, int timeout);
int main(int argc, char **argv)
{
if (argc != 2 )
{
printf ("usage: %s [command]\n" , argv[0 ]);
}
if (0 != system_timeout(argv[1 ], 50 ))
{
printf ("system_timeout error\n" );
return -1 ;
}
printf ("system_timeout success\n" );
return 0 ;
}
int _system_timeout(const char *cmdstring, int timeout)
{
pid_t pid;
int status;
struct sigaction ignore, saveintr, savequit;
sigset_t chldmask, savemask;
if (cmdstring == NULL)
return 1 ;
ignore.sa_handler = SIG_IGN;
sigemptyset(&ignore.sa_mask);
ignore.sa_flags = 0 ;
if (sigaction(SIGINT, &ignore, &saveintr) < 0 )
{
return -1 ;
}
if (sigaction(SIGQUIT, &ignore, &savequit) < 0 )
{
return -1 ;
}
sigemptyset(&chldmask);
sigaddset(&chldmask, SIGCHLD);
if (sigprocmask(SIG_BLOCK, &chldmask, &savemask) < 0 )
{
return -1 ;
}
if ((pid = fork()) < 0 )
{
return -1 ;
}
else if (pid == 0 )
{
sigaction(SIGINT, &saveintr, NULL);
sigaction(SIGQUIT, &savequit, NULL);
sigprocmask(SIG_SETMASK, &savemask, NULL);
execl("/bin/sh" , "sh" , "-c" , cmdstring, (char *)0 );
_exit(127 );
}
else
{
usleep(timeout * 10000 );
kill(pid, SIGKILL);
waitpid(pid, &status, 0 );
}
if (sigaction(SIGINT, &saveintr, NULL) < 0 )
{
return -1 ;
}
if (sigaction(SIGQUIT, &savequit, NULL) < 0 )
return -1 ;
if (sigprocmask(SIG_SETMASK, &savemask, NULL) < 0 )
return -1 ;
return status;
}
int system_timeout(const char *cmdstring, int timeout)
{
int ret = 0 ;
struct sigaction chldnew, chldold;
if (cmdstring == NULL)
return -1 ;
bzero(&chldnew, sizeof (struct sigaction));
bzero(&chldold, sizeof (struct sigaction));
chldnew.sa_handler = SIG_DFL;
sigemptyset(&chldnew.sa_mask);
chldnew.sa_flags = 0 ;
if (sigaction(SIGCHLD, &chldnew, &chldold) < 0 )
{
return -1 ;
}
if ((timeout * 10000 ) < 0 )
{
return -1 ;
}
else if (timeout == 0 )
{
ret = system(cmdstring);
}
else
{
ret = _system_timeout(cmdstring, timeout);
}
if (sigaction(SIGCHLD, &chldold, NULL) < 0 )
{
return -1 ;
}
return ret;
}