2017-04-21 3 views
1

私はAというアプリケーションを持っており、入力はです。コマンドが実行に時間がかかりすぎる場合にスクリプトを中止する

私は、次のような単純なbashスクリプトでnの増加サイズのAを実行したい:私も非常に重要な何かを必要とするしかし

#!/bin/sh 

time ./A 10 
time ./A 20 
time ./A 30 
. 
. 
. 

timeコールが実行に時間がかかりすぎる場合は、入力が大きいため、実行を停止するにはbashスクリプト全体が必要です。

これを行う簡単な方法はありますか?

+2

私はここで編集しましたが、今後は個々の質問に固有の質問のタイトルを作成してください。他の人は - タイトルを見て - 既存の質問とその答えが問題の解決に役立つでしょう。 –

+1

[コマンドラインコマンドを複製して一定時間後にコマンドを自動終了する](http://stackoverflow.com/questions/601543/command-line-command-to-auto-kill-a-command-特定の時間後) – Evert

+1

@Evert、ここでは、個々のコマンドだけでなく、スクリプト全体を中止することが意図されているため、ここでは少し異なります。認可された、非常に異なる*ではありません。 –

答えて

1

次のことができる:

#! /bin/bash                     

timeout 2 time sleep 1                   
if [[ $? == 124 ]]                    
then                       
    exit;                      
fi                        

timeout 2 time sleep 3                   
if [[ $? == 124 ]]                    
then                       
    exit;                      
fi                        

timeout 2 time sleep 5                   
if [[ $? == 124 ]]                    
then                       
    exit;                      
fi                        

0.00user 0.00system 0:01.00elapsed 0%CPU (0avgtext+0avgdata 1696maxresident)k 
0inputs+0outputs (0major+73minor)pagefaults 0swaps 

ないきれいな出力をしますが、最初の行の後に停止します:

は私のシステムでは、それが生産するタイミングsleep 3の結果とsleep 5が示されることはありません。

timeoutはGNU coreutilsコマンドであり、どこにもインストールされていないことに注意してください(システムにインストールできる場合)。終了ステータスも異なる場合があります:124がデフォルトですが、おそらく$? != 0をテストする方が良いでしょう。

+2

あなたは '$?'対 '$ 0'を意味しますか? –

+0

@CharlesDuffy whoops;一定 – Evert

1

1つのアプローチは、同時に背景でsleepとプロセスを開始し、誰が最初に終了するかを確認することです。

以下、他のバックグラウンド・プロセスが手元にコードの下に開始されていないことを前提としています:もちろん

timeout=30 # set this to the number of seconds you want 

timed_run() { 
    time "[email protected]" 
} 

# use: abort_on_timeout timeout_in_seconds command_here 
abort_on_timeout() { 
    local sleep_pid cmd_pid retval 
    local seconds=$1; shift 
    wait # reap any preexisting background processes so they don't interfere 
    sleep "$seconds" & sleep_pid=$! 
    "[email protected]" & cmd_pid=$! 
    wait; retval=$? 
    if kill -0 "$sleep_pid"; then 
    # cmd finished before sleep 
    kill "$sleep_pid" 
    return "$retval" 
    fi 
    # sleep finished before cmd, so exit the whole script 
    kill "$cmd" 
    exit 1 
} 

abort_on_timeout "$timeout" ./A 10 
abort_on_timeout "$timeout" ./A 20 
abort_on_timeout "$timeout" ./A 30 

、あなたはループを使用することができます。

v=10 
while :; do 
    abort_on_timeout "$timeout" ./A "$v" 
    v=$((v + 10)) 
done 
0
const char *env[] = {NULL}; 
const char *argv[] = {NULL}; 
const char *script = "my_script.sh"; 
const int time_interval = 10; 

/* ... */ 

pid_t parent = getpid(); 
pid_t child = vfork(); 
if (child == -1) { 
    printf("Pity! Cannot do vfork\n"); 
} 
else if (child == 0) { 
    execve(script, argv, env); 
} 
else { 
    sleep(time_interval); 
    kill(9, child); 
} 
関連する問題