天天看點

老男孩教育每日一題:2017年3月9日-請解釋下面Shell腳本中if開頭的整行代碼的意思及應用場景嗎?

請解釋下面Shell腳本中 if開頭的整行代碼的意思,你見過它的應用場景麼?

<code>if</code><code>(</code><code>kill</code> <code>-0 $pid 2&gt;</code><code>/dev/du11</code><code>)</code>

<code>then</code>

<code>    </code><code>echo</code><code>"oldboy"</code>

<code>else</code>

<code>   </code><code>echo</code><code>"oldgirl"</code>

<code>fi</code>

面試題:請解釋if (kill -0 $pid 2&gt;/dev/null)代碼的意思?

<code>if</code><code>(</code><code>kill</code> <code>-0 $pid 2&gt;</code><code>/dev/null</code><code>)</code>

<code>    </code><code>then</code>

<code>       </code><code>echo</code> <code>"oldboy"</code>

<code>       </code><code>echo</code> <code>"oldgirl"</code>

老男孩解答要點:

 kill -0 $pid中的-0表示不發送任何信号給PID對應的程序,但是仍會對變量值PID對應的程序是否存在進行檢查,如果$pid對應的程序存在,則傳回0,不存在傳回1。

 2&gt;/dev/null不輸出錯誤資訊。

 系統裡的應用場景是MySQL的/etc/init.d/mysqld腳本中停止MySQL服務的腳本代碼段。

 使用/etc/init.d/mysqld stop指令執行腳本關閉資料庫的程式代碼如下:

  'stop')

    # Stop daemon. We usea signal here to avoid having to know the

    # root password.

    iftest-s"$mysqld_pid_file_path"

    then

      mysqld_pid=`cat "$mysqld_pid_file_path"`

      if (kill-0$mysqld_pid2&gt;/dev/null)

      then

        echo$echo_n"Shutting down MySQL"

        kill$mysqld_pid

        # mysqld shouldremove the pid file when it exits, so wait for it.

        wait_for_pid removed "$mysqld_pid""$mysqld_pid_file_path"; return_value=$?

      else

        log_failure_msg "MySQL server process #$mysqld_pidis not running!"

        rm"$mysqld_pid_file_path"

      fi

      # Delete lock forRedHat / SuSE

      if test-f"$lock_file_path"

        rm-f"$lock_file_path"

      exit$return_value

    else

      log_failure_msg "MySQLserver PID file could not be found!"

    fi

    ;;本文轉自 李導 51CTO部落格,原文連結:http://blog.51cto.com/lidao/1911141