Reputation: 3722
I try to Lock()
file for reading from another process, so I tried to do it in next way:
var (
mutex = sync.Mutex{}
)
func main() {
fmt.Println("Start")
go runZiper()
mutex.Lock()
defer mutex.Unlock()
f2, _ := os.Open("test_tmp.txt")
// here will be writing to file
time.Sleep(3 * time.Second) //just for try
f2.Close()
}
func runZiper() { // this process will compress file (files) in some period
time.Sleep(1 * time.Second) //just for try
f, err := os.Create("test_tmp.txt.zip")
if err != nil { ... }
defer f.Close()
w := zip.NewWriter(f)
data, err := ioutil.ReadFile("test_tmp.txt")
if err != nil { ... }
fz, _ := w.Create("zipped.txt")
fz.Write(data)
w.Close()
}
but my compressor
(function runZip
) still can read and compress the opened file. So that I can lose information.
How can I avoid this situation?
I've tried to use sync.Mutex
and sync.RWMutex
but results were the same.
Upvotes: 1
Views: 890
Reputation: 507
I think there has a smart way to solve this problem. when you close this file you can change the name of this file. On the other hand, we use the compressor to read another name like test_tmp1.txt.
func main() {
go runZiper()
f2, _ := os.Open("test_tmp.txt")
// here will be writing to file
time.Sleep(3 * time.Second) //just for try
f2.Close()
err := os.Rename("test_tmp.txt", "test_tmp1.txt")
if err != nil {
fmt.Println(err)
}
}
func runZiper() { // this process will compress file (files) in some period
time.Sleep(1 * time.Second) //just for try
f, err := os.Create("test_tmp.txt.zip")
if err != nil {
fmt.Println("test_tmp.txt.zip")
}
defer f.Close()
w := zip.NewWriter(f)
data, err := ioutil.ReadFile("test_tmp1.txt")
if err != nil {
fmt.Println("failed")
}
fz, _ := w.Create("zipped.txt")
fz.Write(data)
w.Close()
}
Upvotes: 2