sync_file_fn/
sync_file_fn.rs

1
2use std::io::Write;
3use std::fs::OpenOptions;
4use cluFlock::ExclusiveFlock;
5
6fn main() -> Result<(), std::io::Error> {
7	//Two and more applications consistently write down data in the file.
8	
9	let program_pid = platform_methods::get_pid();
10	println!("[{}] Init...", program_pid);
11	
12
13	let mut file = OpenOptions::new().write(true).append(true).create(true).open("./async_file")?;
14	let mut metadata = file.metadata()?;
15
16	let mut new_len;
17	let mut old_len = metadata.len();
18	for num in 0..200 {
19		println!("[{}][{}] Wait Mod file, {:?}", program_pid, num, file);
20		while old_len == {new_len = {metadata = file.metadata()?; metadata.len()}; new_len} {
21			#[allow(deprecated)]
22			::std::thread::sleep_ms(200);
23		}
24		
25		println!("[{}][{}] WaitLock file, {:?}", program_pid, num, file);
26
27		
28		let result = ExclusiveFlock::wait_lock_fn(&mut file, 
29			|mut file| {
30				println!("[{}][{}] Write file, {:?}", program_pid, num, file);
31				
32				if let Err(e) = write!(file, "[{}][{}]{}->{}\n", program_pid, num, old_len, new_len) {
33					return Err(e);
34				}
35				
36				if let Err(e) = file.sync_all() {
37					return Err(e);
38				}
39				
40				metadata = file.metadata()?;
41				new_len = metadata.len();
42				old_len = new_len;
43
44				Ok(())
45			},
46			|err| Err(err.into_err())
47		)?;
48
49		println!("{:?}", result);
50	}
51
52	Ok( () )
53}
54
55pub mod platform_methods {
56	#[inline(always)]
57	#[cfg(unix)]
58	pub fn get_pid() -> i32 {
59		unsafe { libc::getpid() }
60	}
61
62	#[inline(always)]
63	#[cfg(not(unix))]
64	pub fn get_pid() -> i32 {
65		0
66	}
67}
68