用popen()来调用一个shell命令? [英] Using popen() to invoke a shell command?

查看:377
本文介绍了用popen()来调用一个shell命令?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当运行到x code以下code,我得到不一致的行为。有时它正确打印Git版本,其他时候不打印任何东西。从shell命令的返回code始终为0,但。为什么这可能是任何想法?我在做什么错了?



的#define BUFFER_SIZE 256
INT主(INT ARGC,为const char * argv的[])
{
    FILE * fpipe;
    字符*命令=/选择/ local / bin目录/混帐--version
    焦线[BUFFER_SIZE];    如果(!(fpipe =(FILE *)的popen(指挥,R)))
    {//如果fpipe为NULL
        PERROR(用管道问题);
        出口(1);
    }    而(与fgets(行,sizeof的(字符)* BUFFER_SIZE,fpipe))
    {
         //不一致(有时会发生)
         的printf(READING LINE);
         的printf(%S,行);
    }    INT状态= pclose函数(fpipe);    如果(状态!= 0)
    {
        //从未发生过
        的printf(奇怪的错误code:%D状态);
    }    返回0;
}


解决方案

我想我已经找到了奇怪的行为的根源。这似乎为X code是做一些在建在导致我没有看到在输出终端窗口时髦。如果我尝试直接在此行为不会出现一个标准的终端窗口中运行code和文本始终打印出来。

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;
}

解决方案

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.

这篇关于用popen()来调用一个shell命令?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆