欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

浅谈shell中的clear命令实现

程序员文章站 2024-01-29 22:50:22
...

NAME(名称)

clear - 清除终端屏幕

SYNOPSIS(总览)

clear

DESCRIPTION(描述)

  • clear可以在允许的情况下清屏.
  • 它会在环境变量中查找终端的类型, 然后到terminfo数据库中找出清屏的方法.
    《man手册》
 #include <stdio.h>

int clear_main(int argc, char **argv) {
    /* This prints the clear screen and move cursor to top-left corner control
    * characters for VT100 terminals. This means it will not work on
    * non-VT100 compliant terminals, namely Windows' cmd.exe, but should
    * work on anything unix-y. */
    fputs("\x1b[2J\x1b[H", stdout);
    return 0;

fflush(stdout):清空输出缓冲区,并把缓冲区内容输出。

“\x1b[2J”,//清除整个屏幕,行属性变成单宽单高,光标位置不变

“\x1b[H”,//光标移动

代码测试

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>

int main()
{
    int pid = fork();

    if(pid > 0)
    {
        while(1)
        {
            printf(" father \n");
            sleep(1);
        }
    }
    else if(pid == 0)
    {   
        while(1)
        {
            fflush(stdout);
            fputs("\x1b[2J\x1b[H", stdout);
            sleep(5);
        }
    }
    else
    {
        perror("fork");
    }
}

动图展示结果

浅谈shell中的clear命令实现

系统默认是用CTRl + Z 来暂停进程,但是我们把SIGTSTP信号截断,改成CTRl + L 会有什么效果呢?

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <signal.h>


void sigHandler(int sig)
{   
    char * p[8] ;
    printf("ctrl+z\n");
    p[0] = "clear";
    execvp(p[0],p); 
}

int main()
{
    while(1)
    {
     if(signal(SIGTSTP,sigHandler) == SIG_ERR)
        perror("signal"),exit(0);
    }
}

实验结果
浅谈shell中的clear命令实现

这个时候程序退出了。为什么呢