登录
首页 >  Golang >  Go问答

Golang 从 *os.file 进行复制,无需等待 EOF

来源:stackoverflow

时间:2024-04-12 15:12:34 180浏览 收藏

今天golang学习网给大家带来了《Golang 从 *os.file 进行复制,无需等待 EOF》,其中涉及到的知识点包括等等,无论你是小白还是老手,都适合看一看哦~有好的建议也欢迎大家在评论留言,若是看完有所收获,也希望大家能多多点赞支持呀!一起加油学习~

问题内容

我正在尝试使用 io.copy 从 go 中的文件进行复制,该文件在实际将字节复制出其内部缓冲区之前会等待 eof,对吗?在我的用例(pty/ssh 会话)中,eof 仅在会话完成时出现,这意味着我一直在盲目飞行,直到会话决定结束。

我尝试过一次使用 1 个字节的 copyn,这确实有效,但是如果我尝试等待某一位文本出现,然后复制一个已推送到文件的内容,则代码将挂起并且我失去了会话。是否有一个函数可以“读取那里的内容”然后停止,或者有一个不同的标记(如 eof)可以告诉复制现在停止?

我还尝试读取 ptyi.pty 指向的文件的内容,但它总是返回 0 字节,因此我无法检查那里的更新

这是现在处理它的代码:

type PtyInterface struct {
    pty          *os.File
    buf          *bytes.Buffer
}

func (ptyI *PtyInterface) PrivCmd(cmdStr string) (string, error) {

    // Copy the command provided into the STDIN of the bash shell we opened with
    // the earlier PtyInterface
    _, _ = io.Copy(ptyI.pty, strings.NewReader(string("somecommand")))

    // Assuming everything has gone well, we wait for the prompt to appear

    // We do this by running through individual bytes until the prompt is
    // fully printed (otherwise we might try to send in the answer at the wrong time)
    for !strings.HasSuffix(ptyI.buf.String(), "Prompt question? ") {
        _, _ = io.CopyN(ptyI.buf, ptyI.pty, 1)
    }

    // Once we hit the prompt we throw the answer into STDIN along with a newline
    // and the bash shell should accept this and begin executing the command.
    _, _ = io.Copy(ptyI.pty, strings.NewReader(string("answer\n")))

    // If we dont throw an exit in there then the PTY will never receive an EOF marker and we'll
    // hang on the next copy
    _, _ = io.Copy(ptyI.pty, strings.NewReader(string("exit\n")))

    // Now this copy will wait for an EOF
    _, _ = io.Copy(ptyI.buf, ptyI.pty)

    //Debug info to be printed after
    fmt.Println("\nBytes written to buffer (newone): \n" + ptyI.buf.String())

    return ptyI.buf.String(), nil
}

解决方案


io.copy 视为批量复制或流的便利函数,而不是请求/响应模式的正确工具。

只需检查每个字节是否与消息匹配,即可将字节累积到消息中。直接使用read方法。

func expect(message string, r io.reader) (resp string, err error) {
    b := []byte{0} // 1 byte buffer
    var n int

    for err == nil {
        n, err = r.read(b)
        if n == 0 {
            continue
        }
        resp += string(b[0])
        if strings.hassuffix(resp, message) {
            return resp, err
        }
    }

    return resp, err
}

在您的示例中,您可以这样使用:

resp, err := Expect("Prompt question? ", ptyI.pty)

这是使用模拟连接 io.reader: playground 进行的演示。

文中关于的知识介绍,希望对你的学习有所帮助!若是受益匪浅,那就动动鼠标收藏这篇《Golang 从 *os.file 进行复制,无需等待 EOF》文章吧,也可关注golang学习网公众号了解相关技术文章。

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>