Shell How to pipe program output after it has been executed?

Hi!

I wonder if it's possible to do the thing that I've described in the title?
Suppose that I have two scripts:

foo:
sh:
#!/bin/sh

idx=0
while [ $idx -le 10 ]; do
    echo $idx
    idx=$((idx + 1))
    sleep 1
done

bar:
sh:
#!/bin/sh

while read line; do
    echo "The pipe received: $line"
done

Now, suppose that I executed ./foo, and, before it had finished, I realized that I forgot to pipe its output to another program ( ./bar). That's what I've tried:

Suspend the program by means of sending Ctrl-Z from keyboard (it will send a SIGTSTP signal(3) to the process). Now try to execute: fg |./bar. But I got fg: No current job error. I tried to also do: fg %1 |./bar, but the result is the same.

Well, some time ago I figured that I can use fg in combination with, say, && in order to execute a program when resumed one finishes. Like that fg && echo Done, now, when ./foo finishes, the Done string is printed. So I expected that the trick with pipe will work too, but it doesn't.

Just of curiosity, I tried to do fg >/tmp/fg.log, but the output from ./foo still goes to tty, and in /tmp/fg.log I have a string ./foo.

Does someone know why we have exactly this behaviour and is it even possible to do the thing that I'm trying to do?

Thanks.
 
Thanks, but honestly I don't know what 'pre-fork feature' means in this context. Could you please elaborate a bit?

The only way to establish an anonymous pipe (as opposed to a named pipe which has a filesystem entry) is the pipe(2) system call. You typically fork(2) afterwards and now the two processes (parent and child) can talk over the pipe. But the endpoints are fixed to specific file descriptions in parent and child and cannot be severed (other than exiting one process) or reconnected to new endpoints after the pipe has been created.
 
[…] Just of curiosity, I tried to do fg >/tmp/fg.log, but the output from ./foo still goes to tty, and in /tmp/fg.log I have a string ./foo.
fg by itself prints on (its) standard output information of the job put back into foreground again. If you redirect it, it gets written to said file.​
Does someone know why we have exactly this behaviour and is it even possible to do the thing that I'm trying to do?
For example upon startup a program may fcntl(2) the file, to name an archaic example set the baud rate (err, that’s ioctl(2) then I guess). This needs to be done for the new file as well, not to mention the program logic of choosing the file configuration. Essentially you have to start the program anew, whether you like it or not.​
Thanks, but honestly I don't know what 'pre-fork feature' means in this context. Could you please elaborate a bit?
cracauer@ refers to the fork(2) system call, the main way of creating new processes. somecommand | anothercommand is an anonymous pipeline, as opposed to name pipe files created with mkfifo(1).​
 
Back
Top