Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Low-level disk I/O in Golang

Tags:

io

go

disk

Wondering if there has been anyone experimenting with low-level disk I/O, such as reading raw sectors, MBR, etc. I've done some digging around myself, but haven't been able to find anything mentioned about it. Most of it is dead ends where someone is talking about Go's native io package.

Any leads would be appreciated.

like image 405
Sly Avatar asked Jan 09 '14 22:01

Sly


1 Answers

I am still new to go so my example is not particularly elegant, but I think this is what you want:

package main

import (
    "syscall"
    "fmt"
)

func main() {
    disk := "/dev/sda"
    var fd, numread int
    var err error

    fd, err = syscall.Open(disk, syscall.O_RDONLY, 0777)

    if err != nil {
        fmt.Print(err.Error(), "\n")
        return
    }

    buffer := make([]byte, 10, 100)

    numread, err = syscall.Read(fd, buffer)

    if err != nil {
        fmt.Print(err.Error(), "\n")
    }

    fmt.Printf("Numbytes read: %d\n", numread)
    fmt.Printf("Buffer: %b\n", buffer)

    err = syscall.Close(fd)

    if err != nil {
        fmt.Print(err.Error(), "\n")
    }
}

Here is a link to the syscall package documentation: http://golang.org/pkg/syscall/

According to this page, this package attempts to be compatible with as many different platforms as possible but it kinda seems to my novice eye like the main target is the Linux API with, of course, go idioms to simplify things. I hope this answers your question!

like image 191
waynr Avatar answered Nov 06 '22 11:11

waynr