动态获得Linux终端的大小(尺寸)

类Unix系统提供一个信号-SIGWINCH,每当终端窗口的大小变化时,就会产生此信号。

示例如下:

#include <stdio.h>  
#include <stdio.h>  
#include <stdlib.h>  
#include <termios.h>  
#include <unistd.h>  
#include <string.h>        
#include <sys/ioctl.h>  
#include "errno.h"  

static int get_screen_width(int *pColum)                           
{//get terminal's width  
	struct winsize size;  

	if(isatty(STDOUT_FILENO)==0)  
	{  
		printf("not a tty\n");  
		return -1;    
	}  

	if(ioctl(STDOUT_FILENO, TIOCGWINSZ, &size)<0)  
	{  
		printf("get win size failed: %s\n", strerror(errno));  
		return -1;    
	}  

	*pColum = size.ws_col;  

	return 0;  
}

static void sig_winch(int signo)
{
	int colum_width = 0;


	if (get_screen_width(&colum_width) == 0)
	{
		printf("SIGWINCH received: terminal width: %d\n", colum_width);
	}
	else
	{
		printf("SIGWINCH received\n");
	}

	if(signal(SIGWINCH, sig_winch) == SIG_ERR)
		perror("signal error");

	return ;
}

int main(void)
{
	if(signal(SIGWINCH, sig_winch) == SIG_ERR)
		perror("signal error");

	while (1);

	return 0;
}


运行上面示例:当手动改变终端窗口的大小时,当前终端的大小就会显示出来


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值