Linux命名管道-MKFIFO查询

时间:2018-08-01 12:20:43

标签: linux named-pipes mkfifo

我在命名的Linux BASH,命名的管道等中还相当陌生。 我正在遵循本文的一个示例: https://www.linuxjournal.com/content/using-named-pipes-fifos-bash 一切正常,并且符合预期。但是,这仅仅是开始。 我希望能够从阅读器中调用编写器脚本,以在管道中的两个脚本之间传递信息,而不必为编写器脚本创建cron作业。

这个想法是有人在没有提升权限的情况下触发了阅读器脚本。 读取器呼叫具有一些硬编码sudo用户的写入器(出于测试目的),评估数据并将结果返回给读取器。 任何建议表示赞赏。

1 个答案:

答案 0 :(得分:0)

据我了解,您需要满足以下条件:

  1. 编写器,侦听将数据写入命名管道的请求。
  2. 读取器,它向写入器发送数据请求,并从命名管道读取数据。
  3. writer进程应以特权用户身份运行,而reader则应以特权不足用户身份运行。

1和2可能与以下脚本一起使用,其中:

  • 编写器在后台运行,并监听请求:sh writer.sh &
  • 运行读取器时,它将向写入器发送信号以触发将数据写入到命名管道中
  • 随后,读取器从管道读取并输出数据。

3之所以不可能,是因为:

  • 具有较低特权的进程无法将信号发送到具有较高特权的进程。参见this
  • 或者,具有较低特权的用户运行的脚本不能启动具有较高特权的另一个脚本(即,读取器不能启动具有较高特权的写入器)

writer.sh

#!/bin/bash

# Store the value of the writer process
echo $$ > /tmp/pid
# Specify location of named pipe
pipe=/tmp/datapipe

# Create Data pipe if it doesn't exist
if [[ ! -p $pipe ]]; then
   echo "Pipe does not exist. Creating..."
   mkfifo $pipe
fi

# Send data to pipe
echo "Hello" >$pipe

# Send data to pipe based on trigger
function write_data {
   echo "Writing data"
   echo "Here is some data" >$pipe &
}

# Kill process based on trigger
function kill {
   echo "Exiting"
   exit
}

# Listen for signals
trap write_data SIGINT
trap kill KILL

# listen
while true; do
   sleep 1;
done

reader.sh

#!/bin/bash
pipe=/tmp/datapipe

# Read the writer pid
pid=$(cat /tmp/pid)  

# Trigger writer to create data
kill -s SIGINT $pid

# Read data from named pipe
if read line <$pipe; then
   echo $line
fi
相关问题