#include <sys/resource.h>
#include <errno.h>
static int CloseAllFd(void)
{
struct rlimit lim;
unsigned int i;
if (getrlimit(RLIMIT_NOFILE, &lim) < 0)
{
return -1;
}
if (lim.rlim_cur == RLIM_INFINITY)
{
lim.rlim_cur = 1024;
}
for (i = 0; i < lim.rlim_cur; i ++)
{
if (close(i) < 0 && errno != EBADF)
{
fprintf(stderr, "CloseAllFd error!!!\n");
return -1;
}
}
return 0;
}
static int ExecCommand( const char *pszCmd)
{
pid_t pid;
int status;
if (pszCmd == NULL)
{
return -1;
}
if((pid = fork()) < 0)//error
{
status = -1;
}
else if(pid == 0)//child
{
//释放fd, 避免孩子进程继承资源导致异常
CloseAllFd();
execl("/bin/sh", "sh", "-c", pszCmd, (char *)0);
_exit(127);
}
else//parent
{
while(waitpid(pid, &status, 0) < 0)
{
if(errno != EINTR)
{
status = -1;
break;
}
}
}
return status;
}
创建子进程释放父进程FD
最新推荐文章于 2022-03-09 17:20:08 发布