本文整理匯總了Golang中syscall.Ftruncate函數的典型用法代碼示例。如果您正苦於以下問題:Golang Ftruncate函數的具體用法?Golang Ftruncate怎麽用?Golang Ftruncate使用的例子?那麽, 這裏精選的函數代碼示例或許可以為您提供幫助。
在下文中一共展示了Ftruncate函數的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Golang代碼示例。
示例1: Truncate
func (f *AzukiFile) Truncate(size uint64) fuse.Status {
f.lock.Lock()
r := fuse.ToStatus(syscall.Ftruncate(int(f.File.Fd()), int64(size)))
f.lock.Unlock()
go event.Notify(event.Trunc, f.File.Name())
return r
}
示例2: main
func main() {
flag.Var(&windowSize, "window-size", "Window size in Go `duration` format (default \"10m\")")
flag.IntVar(&maxRestarts, "max-restarts", 5, "Max `restarts` within window-size duration")
flag.StringVar(&metadataDir, "metadata-dir", "/run/runlimit", "Metadata `dir`, where metadata files are stored")
flag.StringVar(&metadataKey, "metadata-key", "", "Metadata key, which will form part of the metadata file name")
flag.StringVar(&svCmd, "sv-cmd", "", "Command to use to stop a service")
flag.Parse()
if windowSize == 0 || maxRestarts == 0 {
fatal("-max-restarts and/or -window-size cannot be 0")
}
cmdline := flag.Args()
if len(cmdline) < 1 {
fatal("No command supplied")
}
cwd, err := os.Getwd()
assert(err)
if metadataKey == "" {
metadataKey = nonalphanumeric.ReplaceAllString(cwd, "_")
}
metafile := filepath.Join(metadataDir, fmt.Sprintf("%s.meta", metadataKey))
f, err := os.OpenFile(metafile, os.O_RDWR|os.O_CREATE, os.FileMode(0644))
assert(err)
defer f.Close()
assert(syscall.Flock(int(f.Fd()), syscall.LOCK_NB|syscall.LOCK_EX))
metadata := &Metadata{}
if err := json.NewDecoder(f).Decode(metadata); err != nil && err != io.EOF {
warning("metadata corrupted, ignoring...")
}
if limit(metadata, time.Duration(windowSize), maxRestarts) {
signals := make(chan os.Signal)
signal.Notify(signals, syscall.SIGTERM)
if svCmd != "" {
parts, err := shlex.Split(svCmd, true)
assert(err)
go func() {
if out, err := exec.Command(parts[0], parts[1:]...).Output(); err != nil {
warning("command exited abnormally with output %s", string(out))
}
}()
select {
case <-signals:
break
case <-time.After(5 * time.Second):
warning("timed out while waiting for TERM from %s", parts[0])
}
}
fatal("max restart intensity reached")
}
assert(syscall.Ftruncate(int(f.Fd()), 0))
_, err = syscall.Seek(int(f.Fd()), 0, 0)
assert(err)
if err := json.NewEncoder(f).Encode(metadata); err != nil {
warning("could not write metadata: %s", err.Error())
}
assert(chainlib.Exec(cmdline, nil))
}
示例3: Truncate
func (f *loopbackFile) Truncate(size uint64) fuse.Status {
f.lock.Lock()
r := fuse.ToStatus(syscall.Ftruncate(int(f.File.Fd()), int64(size)))
f.lock.Unlock()
return r
}
示例4: LoadShared
func LoadShared(name string) (Memory, error) {
// TODO: portable shm_open
filename := filepath.Join("/dev/shm", name)
if file, err := os.OpenFile(
filename, os.O_RDWR|os.O_CREATE|os.O_EXCL, 0600,
); err == nil {
// new file
defer file.Close()
log.Printf(
"Creating a shared memory object (%s) of size: %d bytes",
filename, storageSize,
)
// TODO: prevent other processes from reading until setup is done
if err := syscall.Ftruncate(
int(file.Fd()), int64(storageSize),
); err != nil {
return nil, err
}
return initMemory(file)
}
file, err := os.OpenFile(filename, os.O_RDWR, 0600)
if err != nil {
return nil, err
}
defer file.Close()
return loadMemory(file)
}
示例5: TruncateTo
// TruncateTo enlarges or shortens the file backing the
// memory map to be size newSize bytes. It only impacts
// the file underlying the mapping, not
// the mapping itself at this point.
func (mm *MmapMalloc) TruncateTo(newSize int64) {
if mm.File == nil {
panic("cannot call TruncateTo() on a non-file backed MmapMalloc.")
}
err := syscall.Ftruncate(int(mm.File.Fd()), newSize)
if err != nil {
panic(err)
}
}
示例6: TestFSetAttr
func TestFSetAttr(t *testing.T) {
fs := &FSetAttrFs{}
dir := MakeTempDir()
defer os.RemoveAll(dir)
state, _, err := MountFileSystem(dir, fs, nil)
CheckSuccess(err)
state.Debug = true
defer state.Unmount()
go state.Loop(false)
fn := dir + "/file"
f, err := os.OpenFile(fn, os.O_CREATE|os.O_WRONLY, 0755)
CheckSuccess(err)
defer f.Close()
_, err = f.WriteString("hello")
CheckSuccess(err)
fmt.Println("Ftruncate")
code := syscall.Ftruncate(f.Fd(), 3)
if code != 0 {
t.Error("truncate retval", os.NewSyscallError("Ftruncate", code))
}
if len(fs.file.data) != 3 {
t.Error("truncate")
}
if state.KernelSettings().Flags&CAP_FILE_OPS == 0 {
log.Println("Mount does not support file operations")
m, _ := json.Marshal(state.KernelSettings())
log.Println("Kernel settings: ", string(m))
return
}
_, err = os.Lstat(fn)
CheckSuccess(err)
if !fs.file.GetAttrCalled {
t.Error("Should have called File.GetAttr")
}
err = os.Chmod(fn, 024)
CheckSuccess(err)
if fs.file.FileInfo.Mode&07777 != 024 {
t.Error("chmod")
}
err = os.Chtimes(fn, 100, 101)
CheckSuccess(err)
if fs.file.FileInfo.Atime_ns != 100 || fs.file.FileInfo.Atime_ns != 101 {
t.Error("Utimens")
}
// TODO - test chown if run as root.
}
示例7: Truncate
// Truncate changes the size of the file.
// It does not change the I/O offset.
// If there is an error, it will be of type *PathError.
func (f *File) Truncate(size int64) error {
if f == nil {
return ErrInvalid
}
if e := syscall.Ftruncate(f.fd, size); e != nil {
return &PathError{"truncate", f.name, e}
}
return nil
}
示例8: Truncate
// Truncate changes the size of the file.
// It does not change the I/O offset.
// If there is an error, it will be of type *PathError.
func (f *File) Truncate(size int64) error {
if err := f.checkValid("truncate"); err != nil {
return err
}
if e := syscall.Ftruncate(f.fd, size); e != nil {
return &PathError{"truncate", f.name, e}
}
return nil
}
示例9: Truncate
func (o *ObjectFile) Truncate(size uint64) fuse.Status {
log.Debugf("[objectfile] Truncate %s", o.name)
o.lock.Lock()
r := fuse.ToStatus(syscall.Ftruncate(int(o.localfile.Fd()), int64(size)))
o.needUpload = true
o.lock.Unlock()
return r
}
示例10: TestFSetAttr
func TestFSetAttr(t *testing.T) {
fs := &FSetAttrFs{}
dir, clean, sync := setupFAttrTest(t, fs)
defer clean()
fn := dir + "/file"
f, err := os.OpenFile(fn, os.O_CREATE|os.O_WRONLY, 0755)
CheckSuccess(err)
defer f.Close()
fi, err := f.Stat()
CheckSuccess(err)
_, err = f.WriteString("hello")
CheckSuccess(err)
code := syscall.Ftruncate(int(f.Fd()), 3)
if code != nil {
t.Error("truncate retval", os.NewSyscallError("Ftruncate", code))
}
sync()
if len(fs.file.data) != 3 {
t.Error("truncate")
}
err = f.Chmod(024)
CheckSuccess(err)
sync()
if fs.file.Attr.Mode&07777 != 024 {
t.Error("chmod")
}
err = os.Chtimes(fn, time.Unix(0, 100e3), time.Unix(0, 101e3))
CheckSuccess(err)
sync()
if fs.file.Attr.Atimensec != 100e3 || fs.file.Attr.Mtimensec != 101e3 {
t.Errorf("Utimens: atime %d != 100e3 mtime %d != 101e3",
fs.file.Attr.Atimensec, fs.file.Attr.Mtimensec)
}
newFi, err := f.Stat()
CheckSuccess(err)
i1 := ToStatT(fi).Ino
i2 := ToStatT(newFi).Ino
if i1 != i2 {
t.Errorf("f.Lstat().Ino = %d. Returned %d before.", i2, i1)
}
// TODO - test chown if run as root.
}
示例11: TestFcntlFlock
// TestFcntlFlock tests whether the file locking structure matches
// the calling convention of each kernel.
// On some Linux systems, glibc uses another set of values for the
// commands and translates them to the correct value that the kernel
// expects just before the actual fcntl syscall. As Go uses raw
// syscalls directly, it must use the real value, not the glibc value.
// Thus this test also verifies that the Flock_t structure can be
// roundtripped with F_SETLK and F_GETLK.
func TestFcntlFlock(t *testing.T) {
if runtime.GOOS == "darwin" && (runtime.GOARCH == "arm" || runtime.GOARCH == "arm64") {
t.Skip("skipping; no child processes allowed on iOS")
}
flock := syscall.Flock_t{
Type: syscall.F_WRLCK,
Start: 31415, Len: 271828, Whence: 1,
}
if os.Getenv("GO_WANT_HELPER_PROCESS") == "" {
// parent
name := filepath.Join(os.TempDir(), "TestFcntlFlock")
fd, err := syscall.Open(name, syscall.O_CREAT|syscall.O_RDWR|syscall.O_CLOEXEC, 0)
if err != nil {
t.Fatalf("Open failed: %v", err)
}
defer syscall.Unlink(name)
defer syscall.Close(fd)
if err := syscall.Ftruncate(fd, 1<<20); err != nil {
t.Fatalf("Ftruncate(1<<20) failed: %v", err)
}
if err := syscall.FcntlFlock(uintptr(fd), syscall.F_SETLK, &flock); err != nil {
t.Fatalf("FcntlFlock(F_SETLK) failed: %v", err)
}
cmd := exec.Command(os.Args[0], "-test.run=^TestFcntlFlock$")
cmd.Env = append(os.Environ(), "GO_WANT_HELPER_PROCESS=1")
cmd.ExtraFiles = []*os.File{os.NewFile(uintptr(fd), name)}
out, err := cmd.CombinedOutput()
if len(out) > 0 || err != nil {
t.Fatalf("child process: %q, %v", out, err)
}
} else {
// child
got := flock
// make sure the child lock is conflicting with the parent lock
got.Start--
got.Len++
if err := syscall.FcntlFlock(3, syscall.F_GETLK, &got); err != nil {
t.Fatalf("FcntlFlock(F_GETLK) failed: %v", err)
}
flock.Pid = int32(syscall.Getppid())
// Linux kernel always set Whence to 0
flock.Whence = 0
if got.Type == flock.Type && got.Start == flock.Start && got.Len == flock.Len && got.Pid == flock.Pid && got.Whence == flock.Whence {
os.Exit(0)
}
t.Fatalf("FcntlFlock got %v, want %v", got, flock)
}
}
示例12: CreateAnonymousFile
func CreateAnonymousFile(size int) (*os.File, error) {
template := "wayland-shared"
dir := os.Getenv("XDG_RUNTIME_DIR")
if dir == "" {
panic("XDG_RUNTIME_DIR not defined.")
}
ret, err := ioutil.TempFile(dir, template)
if err != nil {
return nil, err
}
err = syscall.Ftruncate(int(ret.Fd()), int64(size))
if err != nil {
return nil, err
}
return ret, nil
}
示例13: Do
// Do does what you want: it creates (or opens) a pidfile, exclusively locks it
// and writes the current executing programs PID to it. It returns the file
// descriptor and an error.
func Do(filename string, permissions ...uint32) (*os.File, error) {
if len(permissions) == 0 {
permissions = []uint32{0666}
}
fp, err := os.OpenFile(filename, os.O_CREATE|os.O_RDWR, os.FileMode(permissions[0]))
if err != nil {
return nil, err
}
err = syscall.Flock(int(fp.Fd()), syscall.LOCK_NB|syscall.LOCK_EX)
if err != nil {
return nil, err
}
syscall.Ftruncate(int(fp.Fd()), 0)
syscall.Write(int(fp.Fd()), []byte(fmt.Sprintf("%d", os.Getpid())))
return fp, nil
}
示例14: checkFileCap
func (this *Mmap) checkFileCap(start, lens int64) error {
if start+lens >= this.FileLen {
err := syscall.Ftruncate(int(this.FileFd.Fd()), this.FileLen+APPEND_DATA)
if err != nil {
fmt.Printf("ftruncate error : %v\n", err)
return err
}
this.FileLen += APPEND_DATA
this.FilePointer = start + lens
}
return nil
}
示例15: WriteUpDetailFile
func (this *Detail) WriteUpDetailFile() error {
fout, err := os.Create("./index/detail.up")
defer fout.Close()
if err != nil {
//fmt.Printf("Create %v\n",file_name)
return err
}
err = syscall.Ftruncate(int(fout.Fd()), utils.APPEND_DATA)
if err != nil {
fmt.Printf("ftruncate error : %v\n", err)
return err
}
return nil
}