Brahim
Brahim

Reputation: 838

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

What I want to do is:

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.

Upvotes: 3

Views: 3927

Answers (2)

Petr Skocik
Petr Skocik

Reputation: 60143

( 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 &
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.

Upvotes: 7

Dilettant
Dilettant

Reputation: 3345

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 ;-)

Upvotes: 2

Related Questions