Вопрос

I have a command that contains array in there, and I use popen in my c code in Linux.

It works in centOS, Fedora, open SUSE, Redhat, but it always have syntax error on Ubuntu.

Here's a part of code.

fp = popen("counter=0;network=$(ls /sys/class/net);num_re=\"^[0-9]+$\";"
        "for i in $network;"
        "do"
        " recv=$(cat /sys/class/net/$i/statistics/rx_bytes) trans=$(cat /sys/class/net/$i/statistics/tx_bytes)"
        " r1+=(\"$recv\") t1+=(\"$trans\");"
        "done;","r");

It will say -> sh: 1: Syntax error: "(" unexpected (expecting "done")

If I remove r1+=..... t1+=......, and it will pass the syntax checking.

I also try writing it into script, and it works.

Do anyone know the problem?

Thanks.

Это было полезно?

Решение

Yes. Because Ubuntu's default shell (/bin/sh) is dash and not bash. You might use bash like so -

#include <stdio.h>

int main () {
  FILE *fp;
  char *cmd = "bash -c 'counter=0;network=$(ls /sys/class/net);"
    "num_re=\"^[0-9]+$\";for i in $network;do"
    " recv=$(cat /sys/class/net/$i/statistics/rx_bytes) "
    "trans=$(cat /sys/class/net/$i/statistics/tx_bytes)"
    " r1+=(\"$recv\") t1+=(\"$trans\");" "done; echo $r1 $t1'";
  fp = popen (cmd, "r");
  while (1) {
    int c = fgetc (fp);
    if (c == '\0' || feof(fp)) {
      break;
    }
    printf ("%c", c);
  }
}

Which outputs

$ sudo ifconfig eth0 up
$ ./a.out 
0 0
$ ./a.out 
289 762
$ uname -a
Linux eeyore 3.8.0-35-generic #50-Ubuntu SMP Tue Dec 3 01:24:59 UTC 2013 x86_64 x86_64 x86_64 GNU/Linux
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top