views:

777

answers:

2

I use echo in Upstart scripts to log things:

script
    echo "main: some data" >> log
end script

post-start script
    echo "post-start: another data" >> log
end script

Now these two run in parallel, so in the logs I often see:

main: post-start: some data another data

This is not critical, so I won't employ proper synching, but thought I'd turn auto flush ON to at least reduce this effect. Is there an easy way to do that?

Update: yes, flushing will not properly fix it, but I've seen it help such situations to some degree, and this is all I need in this case. It's just that I don't know how to do it in Shell

A: 

Why do you assume that flushing would help? The write done by echo includes a newline, so if the first script ran to completion before the second, the newline would already by there.

In the output it isn't, which indicates that the second script was run before the first was complete, thus interleaving their outputs.

Flushing won't help with this, it's a "proper" parallel race condition.

unwind
flushing won't fix this completely but will make the writing slightly mode atomic, which will reduce the probability of this happening.I didn't really give the exact output or the exact commands, so please don't rely on them too much. The real output is different.
n-alexander
+1  A: 

Try changing:

echo "text"

To:

cat << EOF
text
EOF
Randy Proctor
what's the difference?
n-alexander
I suspected they might write differently (different buffer sizes, etc.), and it worked for me. Of course you can't entirely fix the problem without locking of some sort, but choice of write method might make it less noticeable.
Randy Proctor
I guess that's true. The echo is a built-in command, so it caches, when cat is an executable, so it'll flush when exiting. Thanks
n-alexander