C语言典型代码---执行shell命令并判断是否成功

时间:2022-09-02 23:31:01

C语言调用shell命令,并判断执行是否成功

int smart_system(char* cmd ,int type)
{
    pid_t status;  
    FILE *fp;

    char cIndex[CMD_NOR_LEN] = {0};

    memset(cIndex, 0, CMD_NOR_LEN);

    if(type == RES_RM)
    {
        sprintf(cIndex, "%s >/dev/null 2>&1",cmd);
    }
    else if(type == RES_DTRM)
    {
        sprintf(cIndex, "%s 2>/dev/null",cmd);
    }

    status = system(cIndex);  

    if (-1 == status)  
    {  
        smart_log(ERROR,"CMD ERROR-1",cIndex);
        return RES_CMD_FAIL;
    }  
    else  
    {  
        if (WIFEXITED(status))  
        {  
            if (0 == WEXITSTATUS(status))  
            {  
                return RES_CMD_SUCCESS;
            }  
            else  
            {  
                //sprintf(pores,"run shell script fail, script exit code: %d\n",WEXITSTATUS(status));  
                smart_log(ERROR,"CMD ERROR -2",cIndex);
                return RES_CMD_FAIL;
            }  
        }  
        else  
        {  
            //sprintf(pores,"exit status = [%d]\n", WEXITSTATUS(status));  
            smart_log(ERROR,"CMD ERROR-3",cIndex);
            return RES_CMD_FAIL;
        }  
    }
}