【发布时间】:2016-10-06 08:20:26
【问题描述】:
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 到达之前就消失了吗?
【问题讨论】:
-
当
main返回时程序退出。没有什么能阻止main在文件写入之前退出。 -
这似乎是原因。谢谢。我现在觉得有点傻。你想把它作为答案让我接受吗?