How to stop io.CopyN

I have some code that copies from a file to a tcp socket (like ftp server) and wants to abort this copy if possible.

I'm just using io.CopyN (socket, file, size) and don't see any way to signal interrupt. Any ideas?

+3


source to share


2 answers


CopyN

tries to copy N bytes. If you want to copy less than N bytes then don't use CopyN in the first place. I would probably adapt the original code to something like (untested code):



func copyUpToN(dst Writer, src Reader, n int64, signal chan int) (written int64, err error) {
    buf := make([]byte, 32*1024)
    for written < n {
        select {
        default:
        case <-signal:
            return 0, fmt.Errorf("Aborted") // or whatever
        }

        l := len(buf)
        if d := n - written; d < int64(l) {
            l = int(d)
        }
        nr, er := src.Read(buf[0:l])
        if nr > 0 {
            nw, ew := dst.Write(buf[0:nr])
            if nw > 0 {
                written += int64(nw)
            }
            if ew != nil {
                err = ew
                break
            }
            if nr != nw {
                err = io.ErrShortWrite
                break
            }
        }
        if er != nil {
            err = er
            break
        }
    }
    return written, err
}

      

+3


source


How to close the input file only? io.CopyN

then will return an error and abort.

Here is a demonstration (if you do not work on Linux, replace /dev/zero

and /dev/null

at the equivalent of your operating system!)

package main

import (
    "fmt"
    "io"
    "log"
    "os"
    "time"
)

func main() {
    in, err := os.Open("/dev/zero")
    if err != nil {
        log.Fatal(err)
    }

    out, err := os.Create("/dev/null")
    if err != nil {
        log.Fatal(err)
    }

    go func() {
        time.Sleep(time.Second)
        in.Close()
    }()

    written, err := io.CopyN(out, in, 1E12)
    fmt.Printf("%d bytes written with error %s\n", written, err)
}

      



On startup, it will print something like

9756147712 bytes written with error read /dev/zero: bad file descriptor

      

+4


source







All Articles