Brahim Brahim - 1 year ago 163
Linux Question

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:

sleep 10
echo $string > /proc/${pid}/fd/0

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

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

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

myscript(){ tr a-z A-Z; }
rm -f p
mkfifo p
exec 3<>p
myscript <&3 &
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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download