繁体   English   中英

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

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

当我尝试在 shell 脚本的后台运行交互式命令/应用程序时,我遇到了一个问题。 我正在尝试将命令的输出记录到文件中。 但我没有看到该命令将任何内容记录到文件中。 即使在 bash 中执行命令也无法正常工作,因为它被挂起。

示例脚本

#!/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]$ 

您不需要创建后台进程来重定向数据。 您可以执行以下操作,这将创建一个日志文件actions.log ,其中包含您的每个操作。

#! /bin/bash

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

对您来说,这将类似于:

$ a.out > test.log

如果你确实想要一个后台进程,但需要输入数据:

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

如果这不能回答您的问题,请更具体地说明为什么需要创建子进程以及a.out期望什么。 希望这可以帮助!

编辑:
stdout 和 stderr 是两种不同的重定向。
将 stderr 写入文件2> : $ ./a.out 2> error.log
将 stderr 重定向到 stdout 2>&1$ ./a.out > log.log 2>&1

暂无
暂无

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

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