示例#1
1
func sendTTYToCommand(commandUsock *unixsocket.Usock, clientFile *os.File, err error) error {
	if err != nil {
		return err
	}

	return commandUsock.WriteFD(int(clientFile.Fd()))
}
func setFileLock(f *os.File, lock bool) error {
	how := syscall.LOCK_UN
	if lock {
		how = syscall.LOCK_EX
	}
	return syscall.Flock(int(f.Fd()), how|syscall.LOCK_NB)
}
示例#3
0
文件: bolt_unix.go 项目: 40a/bootkube
// flock acquires an advisory lock on a file descriptor.
func flock(f *os.File, exclusive bool, timeout time.Duration) error {
	var t time.Time
	for {
		// If we're beyond our timeout then return an error.
		// This can only occur after we've attempted a flock once.
		if t.IsZero() {
			t = time.Now()
		} else if timeout > 0 && time.Since(t) > timeout {
			return ErrTimeout
		}
		flag := syscall.LOCK_SH
		if exclusive {
			flag = syscall.LOCK_EX
		}

		// Otherwise attempt to obtain an exclusive lock.
		err := syscall.Flock(int(f.Fd()), flag|syscall.LOCK_NB)
		if err == nil {
			return nil
		} else if err != syscall.EWOULDBLOCK {
			return err
		}

		// Wait for a bit and try again.
		time.Sleep(50 * time.Millisecond)
	}
}
示例#4
0
// SetCapacity reloads the size for the loopback device.
func SetCapacity(file *os.File) error {
	if err := ioctlLoopSetCapacity(file.Fd(), 0); err != nil {
		logrus.Errorf("Error loopbackSetCapacity: %s", err)
		return ErrSetCapacity
	}
	return nil
}
示例#5
0
func getFuseConn(local *os.File) (f *os.File, err os.Error) {
	var data [4]byte
	control := make([]byte, 4*256)

	// n, oobn, recvflags, from, errno  - todo: error checking.
	_, oobn, _, _,
		errno := syscall.Recvmsg(
		local.Fd(), data[:], control[:], 0)
	if errno != 0 {
		return
	}

	message := *(*syscall.Cmsghdr)(unsafe.Pointer(&control[0]))
	fd := *(*int32)(unsafe.Pointer(uintptr(unsafe.Pointer(&control[0])) + syscall.SizeofCmsghdr))

	if message.Type != 1 {
		err = os.NewError(fmt.Sprintf("getFuseConn: recvmsg returned wrong control type: %d", message.Type))
		return
	}
	if oobn <= syscall.SizeofCmsghdr {
		err = os.NewError(fmt.Sprintf("getFuseConn: too short control message. Length: %d", oobn))
		return
	}
	if fd < 0 {
		err = os.NewError(fmt.Sprintf("getFuseConn: fd < 0: %d", fd))
		return
	}
	f = os.NewFile(int(fd), "<fuseConnection>")
	return
}
示例#6
0
文件: editor.go 项目: elves/elvish
func setupTerminal(file *os.File) (*sys.Termios, error) {
	fd := int(file.Fd())
	term, err := sys.NewTermiosFromFd(fd)
	if err != nil {
		return nil, fmt.Errorf("can't get terminal attribute: %s", err)
	}

	savedTermios := term.Copy()

	term.SetICanon(false)
	term.SetEcho(false)
	term.SetVMin(1)
	term.SetVTime(0)

	err = term.ApplyToFd(fd)
	if err != nil {
		return nil, fmt.Errorf("can't set up terminal attribute: %s", err)
	}

	/*
		err = sys.FlushInput(fd)
		if err != nil {
			return nil, fmt.Errorf("can't flush input: %s", err)
		}
	*/

	return savedTermios, nil
}
示例#7
0
// ptsname retrieves the name of the first available pts for the given master.
func ptsname(f *os.File) (string, error) {
	var n int32
	if err := ioctl(f.Fd(), syscall.TIOCGPTN, uintptr(unsafe.Pointer(&n))); err != nil {
		return "", err
	}
	return fmt.Sprintf("/dev/pts/%d", n), nil
}
示例#8
0
文件: slavemonitor.go 项目: jcf/zeus
func (mon *SlaveMonitor) startInitialProcess(sock *os.File) {
	for {
		command := mon.tree.ExecCommand
		parts := strings.Split(command, " ")
		executable := parts[0]
		args := parts[1:]
		cmd := exec.Command(executable, args...)
		cmd.Env = append(os.Environ(), fmt.Sprintf("ZEUS_MASTER_FD=%d", sock.Fd()))
		cmd.ExtraFiles = []*os.File{sock}

		// We want to let this process run "forever", but it will eventually
		// die... either on program termination or when its dependencies change
		// and we kill it. when it's requested to restart, err is "signal 9",
		// and we do nothing.
		go func() {
			output, err := cmd.CombinedOutput()
			if err == nil {
				ErrorConfigCommandCrashed(string(output))
			}
			msg := err.Error()
			if len(msg) > 11 && err.Error()[:11] != "exit status" {
				ErrorConfigCommandCouldntStart(err.Error())
			}
		}()

		restartNow := make(chan bool)
		go func() {
			mon.tree.Root.WaitUntilRestartRequested()
			restartNow <- true
		}()

		<-restartNow
		mon.tree.Root.Kill()
	}
}
示例#9
0
// TryExclusive is the non-blocking form of Exclusive and will return an
// error if the lock could not be obtained immediately.
func TryExclusive(file *os.File) error {
	lock := syscall.LOCK_EX | syscall.LOCK_NB
	if err := syscall.Flock(int(file.Fd()), lock); err != nil {
		return err
	}
	return nil
}
示例#10
0
// Implement mmap for windows
func map_file(file *os.File, offset, size int) ([]byte, error) {

	// create the mapping handle
	h, err := syscall.CreateFileMapping(syscall.Handle(file.Fd()), nil, syscall.PAGE_READONLY, 0, uint32(size), nil)
	if err != nil {
		return nil, err
	}

	// perform the file map operation
	addr, err := syscall.MapViewOfFile(h, syscall.FILE_MAP_READ, uint32(offset>>32), uint32(offset), uintptr(size))
	if err != nil {
		return nil, err
	}

	// store the mapping handle
	win_mapper_mutex.Lock()
	win_mapper_handle[addr] = h
	win_mapper_mutex.Unlock()

	// Slice memory layout
	sl := reflect.SliceHeader{Data: addr, Len: size, Cap: size}

	// Use unsafe to turn sl into a []byte.
	bp := *(*[]byte)(unsafe.Pointer(&sl))

	return bp, err
}
示例#11
0
func (g *GraphTool) tarCp(srcName string, tw *tar.Writer) (int64, error) {
	var (
		src *os.File
		err error
	)

	if src, err = os.Open(srcName); err != nil {
		return 0, err
	}
	defer src.Close()

	srcStat, err := src.Stat()
	if err != nil {
		g.logger.Error(err.Error())
	} else if err := unix.Fadvise(int(src.Fd()), 0, srcStat.Size(), unix.MADV_SEQUENTIAL); err != nil {
		g.logger.Error(err.Error())
	}

	if n, err := io.Copy(tw, src); err != nil {
		g.logger.Error(err.Error())
	} else {
		return n, nil
	}

	return 0, nil
}
示例#12
0
文件: shm.go 项目: jsgilmore/shm
// NewBufferFile maps a file to shared memory and returns a handle to the shared memory buffer
func NewBufferFile(file *os.File, size, prot int) (Buffer, error) {
	fi, err := file.Stat()
	if err != nil {
		return nil, err
	}
	sys := fi.Sys().(*syscall.Stat_t)
	if sys.Size != int64(size) {
		return nil, errWrongSize
	}

	// Dup to allow file parameter to be closed regardless
	fd, err := syscall.Dup(int(file.Fd()))
	if err != nil {
		return nil, err
	}
	const flags = syscall.MAP_SHARED
	b, err := syscall.Mmap(fd, 0, size, prot, flags)
	if err != nil {
		return nil, err
	}

	// localFile is nil because fd is from somewhere else
	buf := &sharedBuffer{os.NewFile(uintptr(fd), ""), nil, b, stackToKeep()}
	runtime.SetFinalizer(buf, (*sharedBuffer).finalize)

	return buf, nil
}
示例#13
0
func main() {
	flag.Usage = usage
	flag.Parse()
	if flag.NArg() < 1 {
		usage()
	}

	vtnum, err := strconv.Atoi(flag.Arg(0))
	ck(err)

	consoles := []string{"/dev/console", "/dev/vc/0", "/dev/tty"}
	var f *os.File
	for _, cc := range consoles {
		f, err = os.OpenFile(cc, os.O_RDWR, 0644)
		if err == nil {
			break
		}
	}
	if f == nil {
		fmt.Fprintln(os.Stderr, "chvt: couldn't get file descriptor referring to console")
		os.Exit(1)
	}

	fd := f.Fd()
	_, _, err = syscall.Syscall(syscall.SYS_IOCTL, fd, 0x5606, uintptr(vtnum))
	if err != nil {
		_, _, err = syscall.Syscall(syscall.SYS_IOCTL, fd, 0x5607, uintptr(vtnum))
	}
	f.Close()

	if err != nil {
		fmt.Fprintln(os.Stderr, "chvt:", err)
		os.Exit(1)
	}
}
示例#14
0
func handleSignals(processGroup *ProcessGroup, c <-chan os.Signal, startTime int, sockfile *os.File) {
	for {
		signal := <-c // os.Signal
		syscallSignal := signal.(syscall.Signal)

		switch syscallSignal {
		case syscall.SIGUSR1:
			socketMasterFdEnvVar := fmt.Sprintf("SOCKETMASTER_FD=%d", sockfile.Fd())
			syscall.Exec(os.Args[0], os.Args, append(os.Environ(), socketMasterFdEnvVar))
		case syscall.SIGHUP:
			process, err := processGroup.StartProcess()
			if err != nil {
				log.Printf("Could not start new process: %v\n", err)
			} else {
				if startTime > 0 {
					time.Sleep(time.Duration(startTime) * time.Millisecond)
				}

				// A possible improvement woud be to only swap the
				// process if the new child is still alive.
				processGroup.SignalAll(signal, process)
			}
		default:
			// Forward signal
			processGroup.SignalAll(signal, nil)
		}
	}
}
func fallocate(f *os.File, sz int64) error {
	err := syscall.Fallocate(int(f.Fd()), 0, 0, sz)
	if err == syscall.ENOTSUP {
		return f.Truncate(sz)
	}
	return err
}
func ChAttr(file *os.File, attributes int) error {
	ret, err := C.ioctl_wrap(C.int(file.Fd()), C.FS_IOC_SETFLAGS, (*C.int)(unsafe.Pointer(&attributes)))
	if ret < 0 {
		return errors.New("ioctl failed: " + err.Error())
	}
	return nil
}
示例#17
0
// DebugOut wraps Unbound's ub_ctx_debugout.
func (u *Unbound) DebugOut(out *os.File) error {
	cmode := C.CString("a+")
	defer C.free(unsafe.Pointer(cmode))
	file := C.fdopen(C.int(out.Fd()), cmode)
	i := C.ub_ctx_debugout(u.ctx, unsafe.Pointer(file))
	return newError(int(i))
}
示例#18
0
// TryShare is the non-blocking form of Share and will return an error if the
// lock could not be obtained immediately.
func TryShare(file *os.File) error {
	lock := syscall.LOCK_SH | syscall.LOCK_NB
	if err := syscall.Flock(int(file.Fd()), lock); err != nil {
		return err
	}
	return nil
}
示例#19
0
func createIpvlan(conf *NetConf, ifName string, netns *os.File) error {
	mode, err := modeFromString(conf.Mode)
	if err != nil {
		return err
	}

	m, err := netlink.LinkByName(conf.Master)
	if err != nil {
		return fmt.Errorf("failed to lookup master %q: %v", conf.Master, err)
	}

	mv := &netlink.IPVlan{
		LinkAttrs: netlink.LinkAttrs{
			MTU:         conf.MTU,
			Name:        ifName,
			ParentIndex: m.Attrs().Index,
			Namespace:   netlink.NsFd(int(netns.Fd())),
		},
		Mode: mode,
	}

	if err := netlink.LinkAdd(mv); err != nil {
		return fmt.Errorf("failed to create ipvlan: %v", err)
	}

	return err
}
示例#20
0
func WriteBitcodeToFile(m Module, file *os.File) error {
	result := C.LLVMWriteBitcodeToFD(m.C, C.int(file.Fd()), C.int(0), C.int(0))
	if result == 0 {
		return nil
	}
	return writeBitcodeToFileErr
}
示例#21
0
// Setwinsz Sets the terminal window size.
func (t *Termios) Setwinsz(file *os.File) error {
	_, _, errno := syscall.Syscall(syscall.SYS_IOCTL, uintptr(file.Fd()), uintptr(TIOCSWINSZ), uintptr(unsafe.Pointer(&t.Wz)))
	if errno != 0 {
		return errno
	}
	return nil
}
示例#22
0
文件: fd_plan9.go 项目: Harvey-OS/go
func (fd *netFD) file(f *os.File, s string) (*os.File, error) {
	dfd, err := syscall.Dup(int(f.Fd()), -1)
	if err != nil {
		return nil, os.NewSyscallError("dup", err)
	}
	return os.NewFile(uintptr(dfd), s), nil
}
示例#23
0
// file2py opens a stdC file from a Go os.File.  Note the returned file has
// been newly opened: the caller must close it with C.fclose(retval).
func file2py(f *os.File, mode string) *C.FILE {
	cmode := C.CString(mode)
	defer C.free(unsafe.Pointer(cmode))
	fd := f.Fd()
	file := C.fdopen(C.int(fd), cmode)
	return file
}
示例#24
0
func ReadLastNLines(f *os.File, lines int) (string, error) {
	if lines <= 0 {
		return "", fmt.Errorf("invalid line count")
	}

	stat, err := f.Stat()
	if err != nil {
		return "", err
	}

	data, err := syscall.Mmap(int(f.Fd()), 0, int(stat.Size()), syscall.PROT_READ, syscall.MAP_SHARED)
	if err != nil {
		return "", err
	}
	defer syscall.Munmap(data)

	for i := len(data) - 1; i >= 0; i-- {
		if data[i] == '\n' {
			lines--
		}

		if lines < 0 {
			return string(data[i+1 : len(data)]), nil
		}
	}

	return string(data), nil
}
示例#25
0
文件: link.go 项目: danieltaborda/rkt
// SetupVeth sets up a virtual ethernet link.
// Should be in container netns.
func SetupVeth(contVethName string, mtu int, hostNS *os.File) (hostVeth, contVeth netlink.Link, err error) {
	var hostVethName string
	hostVethName, contVeth, err = makeVeth(contVethName, mtu)
	if err != nil {
		return
	}

	if err = netlink.LinkSetUp(contVeth); err != nil {
		err = fmt.Errorf("failed to set %q up: %v", contVethName, err)
		return
	}

	hostVeth, err = netlink.LinkByName(hostVethName)
	if err != nil {
		err = fmt.Errorf("failed to lookup %q: %v", hostVethName, err)
		return
	}

	if err = netlink.LinkSetUp(hostVeth); err != nil {
		err = fmt.Errorf("failed to set %q up: %v", contVethName, err)
		return
	}

	if err = netlink.LinkSetNsFd(hostVeth, int(hostNS.Fd())); err != nil {
		err = fmt.Errorf("failed to move veth to host netns: %v", err)
		return
	}

	return
}
func GetLock(file *os.File, locktype int) {
	fmt.Println("Acquiring lock on ", file.Name())
	Info.Println("Acquiring lock on ", file.Name())
	syscall.Flock(int(file.Fd()), locktype)
	Info.Println("Acquired exclusive lock on ", file.Name())
	fmt.Println("Acquired filelock on ", file.Name())
}
示例#27
0
func getConnection(local *os.File) (int, error) {
	var data [4]byte
	control := make([]byte, 4*256)

	// n, oobn, recvflags, from, errno  - todo: error checking.
	_, oobn, _, _,
		err := syscall.Recvmsg(
		int(local.Fd()), data[:], control[:], 0)
	if err != nil {
		return 0, err
	}

	message := *(*syscall.Cmsghdr)(unsafe.Pointer(&control[0]))
	fd := *(*int32)(unsafe.Pointer(uintptr(unsafe.Pointer(&control[0])) + syscall.SizeofCmsghdr))

	if message.Type != 1 {
		return 0, fmt.Errorf("getConnection: recvmsg returned wrong control type: %d", message.Type)
	}
	if oobn <= syscall.SizeofCmsghdr {
		return 0, fmt.Errorf("getConnection: too short control message. Length: %d", oobn)
	}
	if fd < 0 {
		return 0, fmt.Errorf("getConnection: fd < 0: %d", fd)
	}
	return int(fd), nil
}
示例#28
0
文件: pty_darwin.go 项目: burke/pty
func ptsname(f *os.File) (string, error) {
	var n [64]byte

	ioctl(f.Fd(), sys_TIOCPTYGNAME, uintptr(unsafe.Pointer(&n[0])))

	return string(n[:]), nil
}
示例#29
0
// flock acquires an advisory lock on a file descriptor.
func flock(f *os.File, exclusive bool, timeout time.Duration) error {
	var t time.Time
	for {
		// If we're beyond our timeout then return an error.
		// This can only occur after we've attempted a flock once.
		if t.IsZero() {
			t = time.Now()
		} else if timeout > 0 && time.Since(t) > timeout {
			return ErrTimeout
		}
		var lock syscall.Flock_t
		lock.Start = 0
		lock.Len = 0
		lock.Pid = 0
		lock.Whence = 0
		lock.Pid = 0
		if exclusive {
			lock.Type = syscall.F_WRLCK
		} else {
			lock.Type = syscall.F_RDLCK
		}
		err := syscall.FcntlFlock(f.Fd(), syscall.F_SETLK, &lock)
		if err == nil {
			return nil
		} else if err != syscall.EAGAIN {
			return err
		}

		// Wait for a bit and try again.
		time.Sleep(50 * time.Millisecond)
	}
}
示例#30
0
// WriteLongName encrypts plainName and writes it into "hashName.name".
// For the convenience of the caller, plainName may also be a path and will be
// converted internally.
func (n *NameTransform) WriteLongName(dirfd *os.File, hashName string, plainName string) (err error) {
	plainName = filepath.Base(plainName)

	// Encrypt the basename
	dirIV, err := ReadDirIVAt(dirfd)
	if err != nil {
		return err
	}
	cName := n.EncryptName(plainName, dirIV)

	// Write the encrypted name into hashName.name
	fdRaw, err := syscallcompat.Openat(int(dirfd.Fd()), hashName+LongNameSuffix,
		syscall.O_WRONLY|syscall.O_CREAT|syscall.O_EXCL, 0600)
	if err != nil {
		tlog.Warn.Printf("WriteLongName: Openat: %v", err)
		return err
	}
	fd := os.NewFile(uintptr(fdRaw), hashName+LongNameSuffix)
	defer fd.Close()
	_, err = fd.Write([]byte(cName))
	if err != nil {
		tlog.Warn.Printf("WriteLongName: Write: %v", err)
	}
	return err
}