【问题标题】:Is it possible to "push" messages to an active bash terminal?是否可以将消息“推送”到活动的 bash 终端?
【发布时间】:2020-03-04 04:38:08
【问题描述】:

例如通知用户某些任务的状态或报告事件。这不仅应该在登录时发生,而且应该在会话的整个生命周期中发生。 如果消息显示被推迟到用户退出应用程序并返回到 shell 时,那也没关系。

首选通用 Linux 解决方案,但仅适用于 Ubuntu 的解决方案也可以。

【问题讨论】:

    标签: linux bash shell ubuntu


    【解决方案1】:

    首先,一些背景。 每个终端都有一个关联的终端设备文件,您可以使用tty 命令获取该文件

     % tty
     /dev/pts/2
    

    如果一个程序写入这个文件,它会出现在终端上。这是一个例子

     % echo "Hi there" > /dev/pts/2
     Hi there
    

    现在,你是否可以写入这个文件取决于文件的权限

     % ls -l /dev/pts/2
     crw------- 1 noufal tty 136, 2 Mar  4 10:32 /dev/pts/2
    

    这意味着我可以写入但其他人无法写入(这是合理的,因为我不希望其他人在我的终端上写入)。 Prashanth 提到的wall 等命令会写入所有用户的终端文件,而不管权限如何,因为它以 tty 用户的组权限运行,并且所有终端设备文件也具有相同的组。注意下面组的执行权限中的s

    % ls -l /usr/bin/wall
    -rwxr-sr-x 1 root tty 27K Mar  7  2018 /usr/bin/wall
    

    您可以单独使用 `

    打开或关闭到终端的广播
    % mesg
    is n
    % ls -l /dev/pts/2
    crw------- 1 noufal tty 136, 2 Mar  4 10:35 /dev/pts/2
    % mesg y
    % ls -l /dev/pts/2
    crw--w---- 1 noufal tty 136, 2 Mar  4 10:35 /dev/pts/2
    

    现在,为了回答您的问题,如果我写入给定 shell 的 tty 文件,则无论那里运行什么,我都可以在该终端中显示内容。需要注意的是,您需要与运行 shell 的用户是同一用户,或者您的程序必须以 sgid tty 身份运行。

    这是一个简单的带注释的 shell 函数,它将在给定的终端上显示正在运行的时钟。

    function dclock () {
        # Both the tput and date redirect their output to the given tty
        # file so that the display occurs over there.
        while true
              do 
                  tput cup 0 50 > $1 # Position the cursor at row 0 column 50 
                  date > $1 # Print the date
                  sleep 1
        done
        }
    

    您可以打开不同的终端 (T),使用 tty 命令找到 tty 文件,然后在当前终端中运行 dclock /dev/pts/whatever 以查看 T 中出现的时钟。

    【讨论】:

      【解决方案2】:

      wall 命令可以向用户发送消息。 我通常用它来通知用户计划的维护。

      http://man7.org/linux/man-pages/man1/wall.1.html

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-08-16
        • 1970-01-01
        • 2014-06-27
        • 2023-03-29
        • 1970-01-01
        • 2023-03-16
        • 1970-01-01
        • 2017-07-17
        相关资源
        最近更新 更多