-1

I need to run some interactive programs under bash. These interactive programs can accept input from stdin to control the state such as pause, resume, stop, etc.

In order to make the best use of idle resources I need to monitor certain indicators (such as the tasks of key services, CPU load, user session conditions, etc.), and then tell the interactive program to start, suspend, or resume based on the monitored conditions.

I cannot always guard these interactive programs, and want it to be set up as automated services. Is there any way to achieve this kind of goal with the smallest possible bash programming?

Similar questions: Pause mining when using computer

woerdous
  • 11
  • 1
  • This kind of question are better fitted for SuperUser, StackOverflow is a programming Q/A website, unless you have some code for us to look at we probably won't be able to help! – Tzig Aug 06 '21 at 12:55

2 Answers2

1

I understand that your requirement is to simulate the character typing to the interactive process on bash.

Names pipes is an easy way! Take the Pause mining when using computer in the problem description as an example, you may refer to the following sample code:

#!/bin/bash
# filename: monitor.sh
FIFO=/opt/mining/myfifo
[[ ! -e $FIFO ]] && { mkfifo $FIFO; }
while true; do
    STATE=... # Obtain the resource status that needs to be monitored, such as services, cpu load.
    [[ X"$STATE" = X"resource_free" ]] && { echo r > $FIFO; } || { echo p > $FIFO; }
    sleep 30 # sleep 30 seconds
done

According to the above code, you first start the interactive program in the background: # tail -f /opt/mining/myfifo | xmrig > /opt/mining/xmrig.log &

Then start the monitoring process by $ monitor.sh


In addition, the following methods can also meet general needs.

1. tmux / screen based solutions

See the method shared by Cristian Ciupitu in this question for details.

2. TIOCSTI ioctl

Linux-like systems have the TIOCSTI ioctl mechanism to push characters to the terminal input buffer.

A ready-made way is to use writevt.c (typing ctrl+v ctrl+m to send return charector on bash)

Sample py code shared by Bruno Bronosky can be found here, which can also easily achieve the goal.

Samanta
  • 11
  • 4
0

You could try using named pipes. Something like:

mkfifo -m 640 /tmp/myprog-controller
cat /tmp/mypro-controller | myprog

And then send your commands to your program by echoing to /tmp/myprog-controller. This is untested though, as you didn't provide any example code, or specify the program you want to use.

EDIT: the correct mode could differ depending on what your program expects, and how it is being run.

suvayu
  • 4,271
  • 2
  • 29
  • 35