Linux C language calls the system command and gets the return value of the command

Idea: open popen, after the command is executed, read fp and read it into the output parameter.
Note: the size should not be too large. Generally 64,128 is enough. With 1024 or 4028, a segmentation fault will occur, and the stack will report an error.
popen() can execute a shell command and read the return value of the command; the  
popen() function starts a process by creating a pipe, calling fork() to generate a child process, and executing a shell to run the command. Standard input and output operations can be performed through this pipe. This pipe must be closed by the pclose() function, not the fclose() function (if fclose is used, a zombie process will be spawned).
The pclose() function closes the standard I/O stream, waits for the command execution to end, and returns the shell's termination status.
If the shell cannot be executed, the termination status returned by pclose() is the same as if the shell had executed exit.

static int get_system_output(char *cmd, char *output, int size)
{
    FILE *fp=NULL;  
    fp = popen(cmd, "r");   
    if (fp)
    {       
        if(fgets(output, size, fp) != NULL)
        {       
            if(output[strlen(output)-1] == '\n')            
                output[strlen(output)-1] = '\0';    
        }   
        pclose(fp); 
    }
    return 0;
}
    memset( &cmd, 0x00, sizeof(cmd));
    snprintf(cmd, sizeof(cmd), "grep \"%s\" %s | cut -d ' ' -f 1", client_mac, net_arp_file);
    my_printf(LOG_MODE_LEVEL_1, "[##lin##]%s(%d) cmd:%s\n",__FUNCTION__,__LINE__, cmd);
    get_system_output(cmd, client_online_tmp, 64);
    my_printf(LOG_MODE_LEVEL_1, "[##lin##]%s(%d) client_online_tmp:%s\n",__FUNCTION__,__LINE__, client_online_tmp);

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325813903&siteId=291194637