简体   繁体   中英

How to send to stdin in bash 10 seconds after starting the process?

What I want to do is:

  • run a process
  • wait 10 seconds
  • send a string to the stdin of the process

This should be done in a bash script.

I've tried:

./script&
pid=$!
sleep 10
echo $string > /proc/${pid}/fd/0

It does work in a shell but not when I run it in a script.

( sleep 10; echo "how you doin?" ) | ./script

Your approach might work on Linux if eg, your scripts stdin is eg, something like a FIFO:

myscript(){ tr a-z A-Z; }
rm -f p
mkfifo p
exec 3<>p
myscript <&3 &
pid=$!
echo :waiting
sleep 0.5
echo :writing
file /proc/$pid/fd/0
echo hi > /proc/$pid/fd/0
exec 3>&-

But this /proc/$pid/fd stuff behaves differently on different Unices.

It doesn't work for your case because your scripts stdin is a terminal. With default terminal settings, the terminal driver will put background proccesses trying to read from it to sleep (by sending them the SIGTTIN signal) and writes to a terminal filedescriptor will just get echoed -- they won't wake up the sleeping background process that's was put to sleep trying to read from the terminal.

What about this (as OP requested it to be done in the script):

#! /bin/bash
./script&
pid=$!
sleep 10
echo $string > /proc/${pid}/fd/0

just proposing the missing element not commenting on coding style ;-)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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