Skip to content

Commit 48f3bfe

Browse files
authored
Merge pull request #92 from cdesiniotis/open-files-as-wronly-in-nvpassthrough
[nvpassthrough] open files as WRONLY before writing
2 parents c948d03 + 95a1425 commit 48f3bfe

1 file changed

Lines changed: 16 additions & 4 deletions

File tree

pkg/nvpassthrough/nvpassthrough.go

Lines changed: 16 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -276,12 +276,12 @@ func (n *nvpassthrough) Unbind(address string) error {
276276

277277
func bind(address string, driver string) error {
278278
driverOverridePath := filepath.Join(pciDevicesRoot, address, "driver_override")
279-
if err := os.WriteFile(driverOverridePath, []byte(driver), 0644); err != nil {
279+
if err := writeFile(driverOverridePath, driver); err != nil {
280280
return fmt.Errorf("failed to set driver_override for %s: %w", address, err)
281281
}
282282

283283
bindPath := filepath.Join(pciDriversRoot, driver, "bind")
284-
if err := os.WriteFile(bindPath, []byte(address), 0644); err != nil {
284+
if err := writeFile(bindPath, address); err != nil {
285285
return fmt.Errorf("failed to bind %s to %s: %w", address, driver, err)
286286
}
287287

@@ -290,7 +290,7 @@ func bind(address string, driver string) error {
290290

291291
func unbind(address string) error {
292292
driverOverridePath := filepath.Join(pciDevicesRoot, address, "driver_override")
293-
if err := os.WriteFile(driverOverridePath, []byte("\n"), 0644); err != nil {
293+
if err := writeFile(driverOverridePath, "\n"); err != nil {
294294
return fmt.Errorf("failed to clear driver_override for %s: %w", address, err)
295295
}
296296

@@ -306,7 +306,7 @@ func unbind(address string) error {
306306
driverName := filepath.Base(driverLink)
307307

308308
unbindPath := filepath.Join(driverPath, "unbind")
309-
if err := os.WriteFile(unbindPath, []byte(address), 0644); err != nil {
309+
if err := writeFile(unbindPath, address); err != nil {
310310
return fmt.Errorf("failed to unbind %s from %s: %w", address, driverName, err)
311311
}
312312

@@ -365,3 +365,15 @@ func getDriver(devicePath string) (string, error) {
365365
}
366366
return "", err
367367
}
368+
369+
func writeFile(path string, s string) error {
370+
f, err := os.OpenFile(path, os.O_WRONLY|os.O_TRUNC, 0644)
371+
if err != nil {
372+
return fmt.Errorf("failed to open file for writing: %w", err)
373+
}
374+
defer f.Close()
375+
if _, err = f.WriteString(s); err != nil {
376+
return fmt.Errorf("failed writing to file: %w", err)
377+
}
378+
return nil
379+
}

0 commit comments

Comments
 (0)