1.使用vfork, 使用子进程调用脚本,注意子进程结束后,需要主动退出,否则可能会在退出此函数后,同父进程一样执行其它部分,若最后进入休眠状态,则可能成为杀不死的进程。
pid_t pid;
if ((pid = vfork()) < 0 )
{
nRet = -1;
goto _exit_out;
}
else if ( pid == 0 )
{
m_nPid = getpid();
char buffer[128];
memset(buffer, 0, sizeof(buffer));
FILE* pipe = _POPEN(cmd, "r");
if ( !pipe ){
LOG_ERR(
"Execute %s, error:%d\n",
cmd, errno);
nRet = -1;
goto _exit_out;
}
LOG(
"------- Begin %s ------, pid is %d\n",
cmd, m_nPid);
while( !feof(pipe) ){
if(fgets(buffer, 128, pipe)){
sCmdOutput += string(buffer);
LOG(
"+ %s",
buffer);
}
}
_PCLOSE(pipe);
LOG(
"------- End %s ------, pid is %d\n",
cmd, m_nPid);
exit(0);
}
else
{
int statusOfChild;
wait(&statusOfChild);
if (WIFEXITED(statusOfChild))
{
LOG(
"Child Process of %d terminated normally.\n",
m_nPid);
}
else
{
LOG(
"Child Process of %d terminated unnormally, status is %d.\n",
m_nPid, statusOfChild);
}
SNPRINTF(strCmd, 256, KILL_PID_INCLUDE_CHILD, m_nPid);
system(strCmd);
LOG(
"Begin kill process by excute [%s]\n",
strCmd);
m_nPid = -2;
}