@@ -3,6 +3,7 @@ package main
33import (
44 "bufio"
55 "context"
6+ "io"
67 "os"
78 "strings"
89 "sync"
@@ -117,7 +118,9 @@ func updateHostsFile() {
117118 lines := []string {}
118119 BeginText := "### BEGIN DOCKER CONTAINERS ###"
119120 EndText := "### END DOCKER CONTAINERS ###"
120- file , err := os .Open ("/tmp/hosts" )
121+ dstPath := "/tmp/hosts"
122+ tmpPath := "/tmp/hosts.tmp"
123+ file , err := os .Open (dstPath )
121124 if err != nil {
122125 println ("Error opening hosts file" )
123126 return
@@ -147,18 +150,26 @@ func updateHostsFile() {
147150 }
148151 lines = append (lines , EndText )
149152 file .Close ()
150- tmpfile , err := os .Create ("/tmp/hosts.tmp" )
153+ tmpfile , err := os .Create (tmpPath )
154+
151155 if err != nil {
152156 println ("Error creating temp hosts file" )
153157 return
154158 }
159+
155160 for _ , line := range lines {
156161 tmpfile .WriteString (line + "\n " )
157162 }
158- tmpfile .Close ()
159- err = os .Rename ("/tmp/hosts.tmp" , "/tmp/hosts" )
163+ tmpfile .Seek (0 , 0 )
164+ defer tmpfile .Close ()
165+ dst , err := os .Create (dstPath )
160166 if err != nil {
161- println ("Error renaming hosts file " , err )
167+ println ("Error creating hosts file" )
168+ return
169+ }
170+ defer dst .Close ()
171+ if _ , err = io .Copy (dst , tmpfile ); err != nil {
172+ println ("Error updating hosts file" )
162173 return
163174 }
164175}
0 commit comments