您如何在Go中获得终端大小? [英] How do you get the terminal size in Go?

查看:106
本文介绍了您如何在Go中获得终端大小?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在Go中获取终端大小.在C中看起来像这样:

How do I get the terminal size in Go. In C it would look like this:

struct ttysize ts; 
ioctl(0, TIOCGWINSZ, &ts);

但是我如何在Go中访问TIOCGWINSZ

But how to i access TIOCGWINSZ in Go

推荐答案

目前,cgo编译器无法处理c函数中的变量参数和c头文件中的宏,因此您无法执行简单的操作

The cgo compiler can't handle variable arguments in a c function and macros in c header files at present, so you can't do a simple

// #include <sys/ioctl.h>
// typedef struct ttysize ttysize;
import "C"

func GetWinSz() {
    var ts C.ttysize;
    C.ioctl(0,C.TIOCGWINSZ,&ts)
}

要使用宏,请使用常量,因此

To get around the macros use a constant, so

// #include <sys/ioctl.h>
// typedef struct ttysize ttysize;
import "C"

const TIOCGWINSZ C.ulong = 0x5413; // Value from Jed Smith's answer

func GetWinSz() {
    var ts C.ttysize;
    C.ioctl(0,TIOCGWINSZ,&ts)
}

但是,cgo仍会在ioctl原型中的...上bar之以鼻.最好的选择是用一个带有特定数量参数的c函数包装ioctl并将其链接到其中.作为一种hack,您可以在上面的注释中导入"C"

However cgo will still barf on the ... in ioctl's prototype. Your best bet would be to wrap ioctl with a c function taking a specific number of arguments and link that in. As a hack you can do that in the comment above import "C"

// #include <sys/ioctl.h>
// typedef struct ttysize ttysize;
// void myioctl(int i, unsigned long l, ttysize * t){ioctl(i,l,t);}
import "C"

const TIOCGWINSZ C.ulong = 0x5413; // Value from Jed Smith's answer

func GetWinSz() {
    var ts C.ttysize;
    C.myioctl(0,TIOCGWINSZ,&ts)
}

我还没有测试过,但是类似的东西应该可以工作.

I've not tested this, but something similar should work.

这篇关于您如何在Go中获得终端大小?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆