douzhenggui8171 2018-07-19 23:32
浏览 33
已采纳

锁定文件以供读取

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.

展开全部

  • 写回答

1条回答 默认 最新

  • doumengbai2031 2018-07-20 00:36
    关注

    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()
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
编辑
预览

报告相同问题?

手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部