1. 程式人生 > >在shell中程式設計實現獲取c函式輸出

在shell中程式設計實現獲取c函式輸出

最近碰到這樣一個問題,通過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