Shell programming: Executing two applications at t

2019-05-09 05:49发布

I have two applications, lets call them APP1 and APP2. I would like that those two execute on parallel on my machine. It is not necessary, that they start at EXACTLY the same time but the should start at roughly the same time. An intial thought was to have a shell script that looks as follows:

./APP1 &
./APP2

Does this the trick or do I need to insert a wait statement to make sure that APP2 starts within a certain time frame?

Thanks

标签: linux shell
5条回答
冷血范
2楼-- · 2019-05-09 06:15

This might be better:

./app1 & ; ./app2 & 

But, as it has been pointed out, shell will start each of these as child processes in a sub-shell. No guarantees are made by the shell about any synchronization between the processes, or about the startup time.

Why do you need these to run in parallel? Perhaps understanding that requirement will get you a better answer.

You could build some very simple startup synchronization into the two programs. Here is the "app1" part of the example.

#!/bin/sh
# app1.sh
# Do any setup, open log files, check for resources, etc, etc...

# Sync with the other app
typeset -i timeout=120 count=0
touch /tmp/app1
while [[ ! -e /tmp/app2 ]] ; do
    if [[ $count -ge $timeout ]] ; then
        print -u2 "ERROR:  Timeout waiting for app2"
        exit 1
    fi
    (( count += 1 ))
    sleep 1 
done

# Do stuff here...

# Clean up
rm /tmp/app1
exit 0
查看更多
贪生不怕死
3楼-- · 2019-05-09 06:15

This will work, and you can even have APP2 start before APP1. If the time is not important but the order is and APP1 MUST start before APP2 then this construction won't give you this guarantee.

You should include a sleep statement if you want to leave a chance to APP1 to run before APP2 is run.

查看更多
ゆ 、 Hurt°
4楼-- · 2019-05-09 06:26

AFAIK shell doesn't guarantee anything about starting times of the programs, but in practice it should start almost at the same time

查看更多
走好不送
5楼-- · 2019-05-09 06:28

Your solution should work in practice.. Otherwise you can use any scheduler like at, cron and similar to start both commands at specific time.

查看更多
欢心
6楼-- · 2019-05-09 06:30

That will work fine.

查看更多
登录 后发表回答