简体   繁体   English

在 shell 脚本中将交互式命令作为后台进程运行

[英]Running a interactive command as a background process in shell script

I am facing an issue when I am trying to run a interactive command/app in the background of the shell script.当我尝试在 shell 脚本的后台运行交互式命令/应用程序时,我遇到了一个问题。 I am trying to log the output of the command to a file.我正在尝试将命令的输出记录到文件中。 But I don't see that command logging anything to the file.但我没有看到该命令将任何内容记录到文件中。 Even executing the command in the bash also did not work as it gets suspended.即使在 bash 中执行命令也无法正常工作,因为它被挂起。

Sample script示例脚本

#!/bin/bash
while true
do
./a.out > test &
PID=$!
sleep 20
kill -9 $PID
done
[@myprog]$ ./a.out &
[1] 3275
Program started

[1]+  Stopped                 ./a.out
[@myprog]$ 

You don't need to create a background process to redirect data.您不需要创建后台进程来重定向数据。 You can do the following, which will create a logfile actions.log which holds your every action.您可以执行以下操作,这将创建一个日志文件actions.log ,其中包含您的每个操作。

#! /bin/bash

while read -p "action " act; do
        echo $act
done > actions.log
exit 0

For you, this would be something like:对您来说,这将类似于:

$ a.out > test.log

If you do want to have a background process, but need to input data:如果你确实想要一个后台进程,但需要输入数据:

$ function inter_child {
    ./inter.sh  <<-EOF
a
b
c
d
EOF
sleep 10
}
$ inter_child &
$ wait
$ cat actions.log 
a
b
c
d

If this doesn't answer your question, please be more specific why you need to create a child process and what's a.out is expecting.如果这不能回答您的问题,请更具体地说明为什么需要创建子进程以及a.out期望什么。 Hope this helps!希望这可以帮助!

EDIT:编辑:
stdout and stderr are two different redirections. stdout 和 stderr 是两种不同的重定向。
Write stderr to file 2> : $ ./a.out 2> error.log将 stderr 写入文件2> : $ ./a.out 2> error.log
Redirect stderr to stdout 2>&1 : $ ./a.out > log.log 2>&1将 stderr 重定向到 stdout 2>&1$ ./a.out > log.log 2>&1

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM