Linux: Using popen to Execute Bash Commands and Get Return Strings

The system command returns an integer value, making it difficult to determine specific outcomes. You can use popen to execute bash commands and retrieve return values. Note that popen captures the standard output as the return string. If you need to get error output content, you must redirect stderr to stdout.

void system_cmd(const char * command, char * result)
{
    FILE *fpRead;
    fpRead = popen(command, "r");
    char buf[1024] = {0};
    memset(buf,'\0',sizeof(buf));
    while(fgets(buf,1024-1,fpRead)!=NULL)
    { 
        if (buf[strlen(buf) - 1] == '\n') {
            buf[strlen(buf) - 1] = '\0'; //remove newline character
        }
        strcpy(result, buf);
    }
    if(fpRead!=NULL)
        pclose(fpRead);
}

Usage example:

    char pid[10]={0};
    system_cmd("pgrep bash", pid);
comments powered by Disqus
Built with Hugo
Theme Stack designed by Jimmy