我試圖在 docker 上運行一個 golang 應用程式。但是當我嘗試將容器中創建的檔案移動到創建的卷所在的檔案夾時,我收到一個錯誤:rename /mygo/newt /mygo/store/newt: invalid cross-device link
我的 golang 代碼
package main
import (
"bufio"
"fmt"
"os"
"path/filepath"
"strings"
)
func main() {
for {
fmt.Println("do you want to create a file,y for yes, n for no")
var ans string
fmt.Scanln(&ans)
if ans == "y" {
var userFile string
fmt.Println("enter name of file")
fmt.Scanln(&userFile)
myfile, err := os.Create(userFile)
if err != nil {
fmt.Printf("error creating file::%v\n", err)
return
}
fmt.Println("enter text to write in file")
reader := bufio.NewReader(os.Stdin)
input, err := reader.ReadString('\t')
if err != nil {
fmt.Println("an error occured while reading::", err)
return
}
input = strings.TrimSuffix(input, "\t")
num, err := myfile.WriteString(input)
if err != nil {
fmt.Println("error while writing to file", err)
}
fmt.Printf("%v characters entered \n", num)
defer myfile.Close()
fmt.Println("created a file", userFile)
fmt.Println("===========")
fmt.Println("moving file to default folder")
pwd, err_pwd := os.Getwd()
if err_pwd != nil {
fmt.Printf("could not get current working directory::%v\n", err_pwd)
}
userFilePath := pwd "/" userFile
fmt.Println(pwd)
destinationFilePath := pwd "/store/" userFile
//destinationFilePath := pwd "/default/" userFile
err_moving := os.Rename(userFilePath, destinationFilePath)
if err_moving != nil {
fmt.Printf("Error occured while moving file::%v\n", err_moving)
return
}
fmt.Println("file moved")
continue
}
pwd, err_pwd := os.Getwd()
if err_pwd != nil {
fmt.Printf("could not get current working directory::%v\n", err_pwd)
}
fmt.Println("enter full path to move to default location")
var userFilePath string
fmt.Scanln(&userFilePath)
userFileName := filepath.Base(userFilePath)
destinationFilePath := pwd "/" userFileName
err_move := os.Rename(userFilePath, destinationFilePath)
if err_move != nil {
fmt.Printf("error occured while moving file:::%v", err_move)
return
}
fmt.Println("file moved")
continue
}
}
dockerfile
FROM golang
WORKDIR /mygo
COPY . .
RUN go build -o app
CMD ["./app"]
運行容器
錯誤后程式退出
uj5u.com熱心網友回復:
在 Linux 中有兩種“重命名”檔案的方法。
將目錄條目移動到新位置,但保持檔案內容不變。
這具有速度快的優點。它的缺點是在將檔案從一個檔案系統移動到另一個檔案系統時不起作用。
創建一個新檔案,將資料復制到新檔案,并洗掉舊檔案。
但是,如果源和目標位于兩個不同的檔案系統上,它將起作用。
方法#1 在這種情況下不起作用。你需要方法#2。
更多資源:
- 這個golang-dev 討論解釋了為什么會發生這種情況。
- 這個問題談到了同樣的問題,但在 C 的背景關系中。
- Go 在
renameat()內部使用系統呼叫。本手冊頁 解釋了它是如何作業的。您遇到的具體錯誤是 EXDEV 錯誤:“oldpath 和 newpath 不在同一個掛載的檔案系統上。(Linux 允許在多個點掛載檔案系統,但 rename() 不能跨不同的掛載點作業,即使相同的檔案系統安裝在兩者上。)”
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/512020.html
