Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is bash > redirection atomic?

I've weird problem with my crontab job. My crontab job does the following:

program > file

Sometimes however file gets filled with random data that I can't explain.

I wonder if it could be the previous crontab job that's taking longer to run and it somehow mixes its results in file with current crontab job?

Overall my question is: is > operation atomic? Meaning if two programs do > file, then the last one to finish will have its data in file?

like image 574
bodacydo Avatar asked Oct 21 '25 00:10

bodacydo


1 Answers

No, it's not atomic. Not even a little bit atomic.

The redirection does two things:

  1. It opens the file by name, creating it if necessary.

  2. It truncates the file.

After that, the utility is started, with its stdin assigned to the opened file.

If two scripts do that more or less at the same time, they will both end up writing the same file, but since they will have independent file descriptors, each process will overwrite the other process's output, resulting in a grand interleaving of bytes, some from one process and some from the other.

Another common race condition relates to the fact that the file is truncated (by the shell) before the utility starts executing. Consequently, even if the utility only writes a single line to the file, it is possible that a concurrent utility which reads the file will find that it is empty.

like image 179
rici Avatar answered Oct 23 '25 14:10

rici



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!