2012年2月1日 星期三

使用C 取得外部shell script回傳值(linux)

有時候我們為了提高程式的彈性,會使用shell script 來做部份的工作
再取得回傳值來判定正常或是異常
以下面的例子…使用script 判斷目錄是否存在~

#!/bin/sh
#check directory

if [ -d $1 ];then
   #do something...
   ls $1
   exit 0
else
   exit 2
fi

可直接在shell 下觀察回傳

echo $?

而在C 語言程式裡…若要取得執行外部shell script 的回傳值的話,如下所示 

#include

int main (int argc,char **argv)
{
    int ret=0;
    ret=system("./checkdir dir1");
    ret >>= 8;
    if (ret==2)
        printf("dir1 does not exist\n");
}

說明:
1.在shell script 裡是透過exit 返回時帶回傳值, 在C 與 shell 裡的慣例 0 為正常結束,非0 則為異常
2.在C 程式裡其中 ret 值要除以256才會得到與shell 傳回相符的值




沒有留言:

張貼留言

How to use simple speedtest in RaspberryPi CLI

  pi@ChunchaiRPI2:/tmp $  wget -O speedtest-cli https://raw.githubusercontent.com/sivel/speedtest-cli/master/speedtest.py --2023-06-26 10:4...