CluelessNoob
CluelessNoob

Reputation: 696

How to detect which parallel process ends first in Linux?

I have 2 programs: known and unknown . I know the output of the known program (which is constant), but I don't know the output of the unknown program (which could be the same as known in some cases). I want to run them parallel on a Linux machine so that both of them get the same CPU power. I found several solutions for this, but the problem I am facing is detecting which program ends first.

I tried echo $(./known & ./unknown) which works fine except that there is no way for me to detect which ended first if both outputs are the same.

I also tried echo $(./known & time ./unknown > /dev/null) but for some reason the output of the time command is always printed before the known command even though I deliberately made unknown slower than known (so it was supposed to be the other way around). The output is something like this:

echo $(./known & time ./unknown >/dev/null)

real    0m2.054s
user    0m3.072s
sys     0m0.000s
b

Here, 'b' is the output of the known command which I expected to be printed first because it is the faster program.

So any idea how I can detect which process ends first?

Upvotes: 1

Views: 148

Answers (2)

LMC
LMC

Reputation: 12777

It can be done by trapping kill signals as below.

Let's say there's a known.sh script

sleep 4
d=$(date '+%H:%M:%S')
echo "known process $d [parent PID: $1]"
kill -SIGUSR1 $1

An unknown.sh script

sleep 1
d=$(date '+%H:%M:%S')
echo "unknown process $d [parent PID: $1]"
kill -SIGUSR2 $1

Finally, a master.sh script that will wait for SIGUSR1 and SIGUSR2 signals

trap 'echo "$k ended"' SIGUSR1 SIGUSR2

echo "I'm the master [PID $$]"
k=$(time ./unknown.sh $$ &)
k=$(time ./known.sh $$ &)
sleep 5

Output of master.sh will be

I'm the master [PID 3205]

real    0m1.005s
user    0m0.004s
sys     0m0.001s
unknown process 00:53:57 [parent PID: 3205] ended

real    0m4.004s
user    0m0.003s
sys     0m0.001s
known process 00:54:01 [parent PID: 3205] ended

Upvotes: 1

CluelessNoob
CluelessNoob

Reputation: 696

Sorry to post my own answer, but I just found a solution. This works:

echo $(./known & echo x$(./unknown))

Here, 'x' is what differentiates the two outputs, so even if they are the same, I know which one was printed first.

Please feel free to answer or comment if you have a better solution. Thanks.

Upvotes: 0

Related Questions