gitee.com/mirrors_u-root/u-root@v7.0.0+incompatible/cmds/core/sync/sync.go (about)

     1  // Copyright 2016-2020 the u-root Authors. All rights reserved
     2  // Use of this source code is governed by a BSD-style
     3  // license that can be found in the LICENSE file.
     4  
     5  // sync command in Go.
     6  //
     7  // Synopsis:
     8  //		sync [-df] [FILE]
     9  //
    10  
    11  package main
    12  
    13  import (
    14  	"flag"
    15  	"fmt"
    16  	"log"
    17  	"os"
    18  	"syscall"
    19  
    20  	"golang.org/x/sys/unix"
    21  )
    22  
    23  var (
    24  	data       = flag.Bool("data", false, "sync file data, no metadata")
    25  	filesystem = flag.Bool("filesystem", false, "commit filesystem caches to disk")
    26  )
    27  
    28  func init() {
    29  	flag.BoolVar(data, "d", false, "")
    30  	flag.BoolVar(filesystem, "f", false, "")
    31  
    32  	flag.Usage = func() {
    33  		fmt.Fprintf(os.Stderr, "Usage: %s [OPTION] [FILE]...\n", os.Args[0])
    34  		flag.PrintDefaults()
    35  	}
    36  }
    37  
    38  func doSyscall(syscallNum uintptr) {
    39  	for _, fileName := range flag.Args() {
    40  		f, err := os.OpenFile(fileName, syscall.O_RDONLY|syscall.O_NOCTTY|syscall.O_CLOEXEC, 0644)
    41  		if err != nil {
    42  			log.Fatal(err)
    43  		}
    44  		_, _, err = syscall.Syscall(syscallNum, uintptr(f.Fd()), 0, 0)
    45  		if err != nil {
    46  			log.Fatal(err)
    47  		}
    48  		f.Close()
    49  	}
    50  }
    51  
    52  func main() {
    53  	flag.Parse()
    54  	switch {
    55  	case *data:
    56  		doSyscall(unix.SYS_FDATASYNC)
    57  	case *filesystem:
    58  		doSyscall(unix.SYS_SYNCFS)
    59  	default:
    60  		syscall.Sync()
    61  		os.Exit(0)
    62  	}
    63  }