您的位置:首页 > 运维架构 > Shell

C语言中system调用shell脚本的问题

2010-03-13 09:46 453 查看
在C语言中使用system()语句调用shell脚本时,C语言程序并不会等待system()语句执行完毕尤其在shell脚本有调用bash下命令时并向文件输出时,又无法用刷新标准输出流缓冲区的方式来解决乱序输出的问题.例如

C中部分

for (int i=0;i<5;i++)

{

     system("./test.sh");

}

shell中部分

cat /dev/null > test.txt

echo -e "output infomation" >> test.txt

nslookup 8.8.8.8 | grep "name =" >> test.txt #nslookup为解析与逆向解析ip地址的命令会因为网络通信而不能即时得到结果

 

在有些低版本的linux中

当这部分执行的时候我们在test.txt文件里面看到的结果有可能是

output infomation

output infomation

output infomation

output infomation

output infomation

8.8.8.8.in-addr.arpa name = google-public-dns-a.google.com

8.8.8.8.in-addr.arpa name = google-public-dns-a.google.com

8.8.8.8.in-addr.arpa name = google-public-dns-a.google.com

8.8.8.8.in-addr.arpa name = google-public-dns-a.google.com

8.8.8.8.in-addr.arpa name = google-public-dns-a.google.com

 

这种情况出现的时候

使用

(echo -e "output infomation" ; nslookup 8.8.8.8) | grep -E 'output information|name ='

就能保证顺序的输出了

 

 

 
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息