试图将Linux命令输出传递给变量

时间:2015-11-13 18:03:58

标签: c linux bash

我有以下代码:

#include <stdio.h>
#include <stdlib.h>

int readCmd(char* cmd) {
    FILE *fp;
    char path[1024];

    /* Open the command for reading. */
    fp = popen(cmd, "r");
    if (fp == NULL) {
        printf("Failed to run command\n" );
        exit(1);
    }

    /* Read the output a line at a time - output it. */
    while (fgets(path, sizeof(path)-1, fp) != NULL) {
        printf("%s", path);
    }
    /* close */
    pclose(fp);
    return path;
}


int main( int argc, char *argv[] ) {
char* gp123;
char* gp124;


gp124=readCmd("cat /sys/class/gpio/gpio124/direction");
gp123=readCmd("cat /sys/class/gpio/gpio123/direction");
printf("123: %s \n124: %s \n",gp123,gp124);

}

使用以下输出:

out
in
123: in
124: in

如您所见,gpio pin 123设置为&#39; in&#39;并且124设置为&#39; out&#39;

然而,gp123和gp124都被分配到&#39;中。我的功能和C都生疏了。你能帮我找一点吗?

更具体地说,为什么我没有为我读过的每个命令分配返回值?这是一个本地/全局变量问题吗?

谢谢!

修改

#include <stdio.h>
#include <stdlib.h>
char* readCmd(char* cmd)
{
FILE *fp;
static char path[1024];

/* Open the command for reading. */
fp = popen(cmd, "r");
if (fp == NULL) {
    printf("Failed to run command\n" );
    exit(1);
}

/* Read the output a line at a time - output it. */
while (fgets(path, sizeof(path)-1, fp) != NULL) {
    printf("%s", path);
}
/* close */
pclose(fp);
return path;
}


int main( int argc, char *argv[] )
{
    char gp123[50];
    char gp124[50];
    char *answer;

    answer=readCmd("cat /sys/class/gpio/gpio124/direction");
    sprintf(gp124, "%s", answer);
    answer=readCmd("cat /sys/class/gpio/gpio123/direction");
    sprintf(gp123, "%s", answer);
    printf("123: %s \n124: %s \n",gp123,gp124);

}

这似乎工作正常,这里有什么我应该改变的更正确吗?

1 个答案:

答案 0 :(得分:1)

您无法从函数返回指向自动内存的指针。路径数组仅在readCmd函数的持续时间内存在(应返回char *,而不是int)。

要解决此问题,您可以:

  • 声明数组静态(或使用全局数组 - 几乎相同)并包含不可重入性
  • 使用堆(malloc数组或使用GNU getline函数)
  • 要求调用者提供指向保存输出的位置的指针(其大小也应该传入)