How do I synchronize from two processes – atomic writes on one file?

I have two processes. Each process writes big data buffer. I want to control the synchronization of these processes to write to a file

Process 1 write buffer a includes (A1, A2, A3) and process 2 write buffer B includes (B1, B2, B3) When we use the write () system call to write these buffers to the disk to the same file (the entire buffer is written once: write (FD, a, sizeof (a))), what is the file architecture?

>It's like this: is a, B or B, a possible? > Or it may be like this: A1, B1, A3

I ask this because system calls are atomic What happens if we write too much data buffer Is it like a pipe for regular disk files?

Solution

If you want to have the contents of two buffers, you must turn on o_ File with append flag The append flag looks for the end of the file before writing Without this setting, both processes may point to the same or overlapping area of the file, and any last written will overwrite the content written by the other

Each write call writes the requested number of bytes If your process is interrupted by a signal, you can eventually make a partial write - returns the actual number of bytes written Whether you write all the bytes or not, you will write a continuous part of the file You don't get the interleaving effect you mentioned as your second possibility (e.g. A1,...)

If you only do part of your writing, the way you work depends on you You can continue to write (offset the number of bytes previously written from the buffer) or discard the rest of the write Only in this way can the interleaving effect be obtained

If it is important to finish a write before another process writes, you should consider locking the file for exclusive write access before attempting to write any data (both processes must check)

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>