2016-10-06 4 views
0
package main 
import (
    "encoding/json" 
    "fmt" 
    "/something/models" 
    "os" 
    "path/filepath" 
    "runtime" 
) 

func WriteDeviceToFile(d chan *models.Device, fileName string) { 

_, b, _, _ := runtime.Caller(0) 
basepath := filepath.Dir(b) 
filePath := basepath + "/dataFile/" + fileName 

var f *os.File 
var err error 


f, _ = os.OpenFile(filePath, os.O_APPEND|os.O_WRONLY, 0600) 

defer f.Close() 


for device := range d { 
    deviceB, err := json.Marshal(device) 
    fmt.Println(string(deviceB)) 
    if err == nil { 
     if _, err = f.WriteString(string(deviceB)); err != nil { 
      panic(err) 
     } 
    } else { 
     panic(err) 
    } 
} 

} 

func main() { 
deviceChan := make(chan *models.Device) 
go WriteDeviceToFile(deviceChan, "notalive.txt") 
d := models.NewDevice("12346", "") 
deviceChan <- d 
d = models.NewDevice("abcd", "") 
deviceChan <- d 
close(deviceChan) 
} 

채널에 전송 된 장치가 두 개 이상인 경우에만 작동합니다. deviceChan에 하나의 장치 만 있으면이 함수는 아무것도 수신하지 않습니다. WriteDeviceToFile이 도착하기 전에 채널이 사라 졌습니까?이동 중에 이상한 채널 동작

+2

'main'이 반환되면 프로그램이 종료됩니다. 파일이 쓰여지기 전에'main'이 빠져 나가는 것을 막을 수는 없습니다. –

+0

그 이유가있는 것 같습니다. 감사. 나는 지금 어리 석다. 그걸 내가 받아 들일 수 있도록 대답으로 넣으시겠습니까? – user3837980

답변

1

main가 반환되면 프로그램이 종료됩니다. 파일을 쓰기 전에 main이 종료하지 못하도록합니다.