在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 ='
就能保证顺序的输出了
本文探讨了在C语言中使用system()调用shell脚本时遇到的输出乱序问题,特别是在shell脚本中有调用网络命令时,并提供了解决方案。
6214

被折叠的 条评论
为什么被折叠?



