[英]using array in ubuntu with popen won't work
I have a command that contains array in there, and I use popen in my c code in Linux. 我有一个包含数组的命令,并且在Linux的C代码中使用popen。
It works in centOS, Fedora, open SUSE, Redhat, but it always have syntax error on Ubuntu. 它可以在centOS,Fedora,open SUSE,Redhat中运行,但在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") 它将显示为-> sh:1:语法错误:“(”意外(期望“完成”)
If I remove r1+=..... t1+=......, and it will pass the syntax checking. 如果删除r1 + = ..... t1 + = ......,它将通过语法检查。
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
. 因为Ubuntu的默认shell(
/bin/sh
)是dash而不是bash
。 You might use bash
like so - 您可能会像这样使用
bash
#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 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.