使bash脚本沿其启动的程序运行,并发送程序输入 [英] Keeping a bash script running along the program it has started, and sending the program input

查看:94
本文介绍了使bash脚本沿其启动的程序运行,并发送程序输入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一个非常简单的脚本来控制进程,
脚本检查该进程是否正在运行,如果没有运行,请执行该程序。

I'm writing a very simple script to control a process, script checks if the process is running, if not: executes it.

I需要扩展此功能,使其具有在指定的时间量后杀死特定流程实例(启动了每个脚本)的能力。
问题是,一旦执行了bash脚本,它就不会运行,直到执行完的程序完成为止。将一些输入传递给进程的能力也很有用,因为我在服务中内置了一个优雅的退出功能

I need to expand this with the ability to kill a specific process instance (very one one script has started) after a specified amount of time. Problem is, once bash script is executed it isn't running until the executed program finishes.Ability to pass some input to the process would also be useful, as I have a graceful exit function built in to the service I'm running.

基本上,我的bash脚本应按照启动过程运行,并在睡眠x超时后通过stdin发送kill命令。

Basically, my bash script should run along the process it's started, and send a kill command via stdin after sleep x times out.

如何将一些脚本输入转发到已启动的流程脚本,以及在执行流程后如何保持脚本运行?

How do I forward some scripted input to the process script has started, and how do I keep the script running after executing the process?

谢谢。

推荐答案

如果要与脚本一起运行进程,则需要在后台运行:

If you want to run the process alongside the script, you need to run it in the background:

command &
pid=$!

现在 pid 将包含您刚刚开始的过程。接下来,您需要一种与流程进行通信的方法。如果只需要向流程发送一些输入,请使用此处文档:

Now pid will contain the PID of the process you just started. Next you need a way to communicate with the process. If you just need to send some input to the process, use a "here document":

command <<EOF
input
more input
even more input
var=$HOME
EOF

如果您仍然需要在后台运行该过程,则将变得更加棘手。将输入写入临时文件(请参见 mktemp(1)):

That gets more tricky if you still need to run the process in the background. Either write the input to a temporary file (see mktemp(1)):

tmp=$(mktemp)
cat > "$tmp" <<EOF
input
more input
even more input
var=$HOME
EOF
command < "$tmp" &
pid=$!

,也可以使用命名管道(FIFO)。 本文应该使您入门。

or you can use named pipes (FIFOs). This article should get you started.

这篇关于使bash脚本沿其启动的程序运行,并发送程序输入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆