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.