2012年8月23日星期四

在shell中编程实现获取c函数输出

http://blog.csdn.net/zhangmuyan/article/details/7568284


最近碰到这样一个问题,通过c语言写了一个程序,然后再shell脚本中获取这个c语言的输出,执行其他的处理,该如何
做?比如,c语言程序输出hello world,通过shell脚本获取到这个输出,然后输出:the first is hello, the second is world.该如何做?
我把我的解决方案整理如下:
1. 编程和编译c语言程序
   源代码如下hello.c:
   #include <stdio.h>
   int main()
   {
      printf("hello world");
      return 1;
   }
   编译程序 : gcc hello.c -o hello;生成了一个可执行文件hello,在Shell中执行hello程序,得到输出hello world
2. 第二步编写脚本
   在shell环境中执行vi sh ,sh脚本的内容如下:
   MYPATH=/home/minrongf
   arg1=$(echo `/home/minrongf/hello` | awk '{print $1 }')
   arg2=$(echo `/home/minrongf/hello` | awk '{print $2 }')
   echo the first is $arg1, the second is $arg2
 
   然后给脚本sh赋与可执行的权限: chmod a+x sh
   然后执行这个脚本,将看到这个输出.
   Shell>./sh
   Shell>the first is hello, the second is world

   在编写脚本的时候,也可以把c语言的结果输入到一个临时文件中,然后处理这个临时文件.
   创建另外一个脚本sh2.脚本内容如下:
 
   MYTMPFILE=/opt/tmp/1.txt
   MYPATH=/home/minrongf
   $MYPATH/hello > $MYTMPFILE
   while read arg1 arg2
   do
      printf " the first is $arg1, the second is $arg2/n"
   done < $MYTMPFILE
   rm $MYTMPFILE

没有评论:

发表评论