0

i am fairly new in the named Linux BASH, named pipes etc. I am following an example from this article: https://www.linuxjournal.com/content/using-named-pipes-fifos-bash All works well and as expected. However this is only the beginning. I would like to be able to call writer script from reader to pass info between the 2 scripts in the pipe without having to create cron job for the writer script.

The idea is that someone triggers the reader script without elevated permissions. The reader calls the writer which has some hard-coded sudo user (for testing purposes), evaluates data and returns the result to the reader. Any advise is appreciated.

  • Please paraphrase the content of the link such that others can answer your question without clicking there. Links tend to rot. – Harald Aug 03 '18 at 15:07

1 Answers1

0

As I understand it, you require the following:

  1. A writer which listens for requests to write data to the named pipe.
  2. A reader which sends requests for data to the writer, and reads the data from the named pipe.
  3. The writer process should run as a privileged user, and the reader should run as an under-privileged user.

1 and 2 are possible with the scripts below, where:

  • The writer is run in the background and listens for requests: sh writer.sh &
  • When the reader is run, it sends a signal to the writer to trigger the writing of data to the named pipe
  • The reader then subsequently reads from the pipe and outputs the data.

3 is not possible because:

  • A process with lower privileges cannot send signals to a process with a higher privilege. See this
  • Alternatively, a script run by a user with lower privileges cannot launch another script with higher privileges (i.e the reader cannot launch a writer with higher privileges)

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
moebius
  • 2,061
  • 11
  • 20
  • Thanks for the comment. I decided in the end to have daemon script running on boot. The script will monitor the pipe and when something goes through it will trigger specific action. – Ivan Kanchev Aug 07 '18 at 09:16