Race condition from creating file and ioutil.ReadFile

polaris · · 493 次点击    
这是一个分享于 的资源,其中的信息可能已经有所发展或是发生改变。
<p>I have a golang end point that receive uploaded file</p> <p>I discover that creating a file and calling <code>iotil.ReadFile</code> immediately will lead to empty data returned even after file sync.</p> <p>The data is only available after the second call to the same function or wait 5 second.</p> <pre><code> r.ParseMultipartForm(32 &lt;&lt; 20) file, handler, err := r.FormFile(&#34;my_input_name&#34;) f, err := os.OpenFile(&#34;./img_dump/&#34;+handler.Filename, os.O_WRONLY|os.O_CREATE, 0666) if err != nil { return } f.Sync() // data is empty [] when first called data, err := ioutil.ReadFile(&#34;/myAbsolutePath/img_dump/&#34; + handler.Filename) c1 := make(chan string, 1) go func() { time.Sleep(time.Second * 5) c1 &lt;- &#34;result 1&#34; }() go func(name string) { select { case _ = &lt;-c1: data, err = ioutil.ReadFile(&#34;/myAbsolutePath/img_dump/&#34; + name) fmt.Println(&#34;after sleep&#34;) // This only works if I don&#39;t try f.Close(), data is not empty fmt.Println(len(data)) } }(handler.Filename) </code></pre> <p>Does anyone know how to avoid race condition between creating and reading a file?</p> <hr/>**评论:**<br/><br/>felixge: <pre><p>I don&#39;t think you&#39;re seeing a race condition. It looks like you&#39;re simply not copying the data from your <code>file</code> instance to your <code>f</code> file?</p></pre>multishotkey: <pre><p>hmm, but I added wait 5 second and it worked, I added that part of the code to the post. </p> <p>edit: actually you are right, another file is populating it in some other goroutine, thanks :)</p></pre>chmikes: <pre><p>Comparing with <a href="https://astaxie.gitbooks.io/build-web-application-with-golang/en/04.5.html" rel="nofollow">this</a> example, you don&#39;t test the returned error from FormFile. There could have been an error. </p> <p>You are also missing the io.Copy() which I guess writes the data in the file. You should also close that file. </p></pre>

入群交流(和以上内容无关):加入Go大咖交流群,或添加微信:liuxiaoyan-s 备注:入群;或加QQ群:692541889

493 次点击  
加入收藏 微博
暂无回复
添加一条新回复 (您需要 登录 后才能回复 没有账号 ?)
  • 请尽量让自己的回复能够对别人有帮助
  • 支持 Markdown 格式, **粗体**、~~删除线~~、`单行代码`
  • 支持 @ 本站用户;支持表情(输入 : 提示),见 Emoji cheat sheet
  • 图片支持拖拽、截图粘贴等方式上传