Using popen() to invoke a shell command?

邮差的信 提交于 2020-01-14 14:01:48

问题


When running the following code through xcode I get inconsistent behavior. Sometimes it prints the git version correctly, other times it doesn't print anything. The return code from the shell command is always 0 though. Any ideas on why this might be? What am I doing wrong?


#define BUFFER_SIZE 256 
int main (int argc, const char * argv[])  
{   
    FILE *fpipe;
    char *command="/opt/local/bin/git --version";
    char line[BUFFER_SIZE];

    if ( !(fpipe = (FILE*)popen(command, "r")) )
    {   // If fpipe is NULL
        perror("Problems with pipe");
        exit(1);
    }

    while ( fgets( line, sizeof(char) * BUFFER_SIZE, fpipe))
    {
         // Inconsistent (happens sometimes) 
         printf("READING LINE");
         printf("%s", line);
    }

    int status = pclose(fpipe);

    if (status != 0)
    {
        // Never happens
        printf("Strange error code: %d", status);
    }

    return 0;
}


回答1:


It sounds suspiciously like as if the output is buffered, have you considered flushing the output buffer..use fflush() to do so. See here for further information.

Hope this helps, Best regards, Tom.




回答2:


I think I have found the source of the strange behavior. It seems as Xcode is doing something funky in the built in terminal window which results in me not seeing the output. If I try to run the code directly in a standard terminal window this behavior does not appear, and the text is consistently printed out.



来源:https://stackoverflow.com/questions/2072676/using-popen-to-invoke-a-shell-command

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!