0

I wish to send a command to process A, from process B, via a FIFO.

The command will be a word or a sentence, but wholly contained on a "\n" terminated line - but could, in general, be a multi-line record, terminated by another character.

The relevant portion of the code that I tried, looks something like this:

Process A:

$ mkfifo ff
$ read x < ff

Process B: (from another terminal window)

$ echo -n "cmd"   > ff
$ echo -n " arg1" > ff
$ echo -n " arg2" > ff
 ...    
$ echo    " argN" > ff

However, what's happening is, the read returns with the value cmd, even though the bash man page says it, by default, reads \n terminated lines, unless the -d delim option is used.

So, I next tried specifying -d delim explicitly,

$ read -d "\n" x < f`

and still the same result.

Could echo -n be closing the FIFO's file 'descriptor'?

I'm using bash 4.4.x on Ubuntu 18.04.

4

Yep, that's exactly what happens:

$ mkfifo p
$ while :; do cat p ; done > /dev/null  & 
$ strace -etrace=open,close bash -c 'echo -n foo > p; echo bar > p' |& grep '"p"' -A1
open("p", O_WRONLY|O_CREAT|O_TRUNC, 0666) = 3
close(3)                                = 0
--
open("p", O_WRONLY|O_CREAT|O_TRUNC, 0666) = 3
close(3)                                = 0

The redirections only take effect for the duration of the single command they're set up on. The workaround on the write side is to either a) use a compound block to group the commands, or b) use exec to open a file descriptor for the duration of the whole script (or until closed).

a)

{ echo -n foo; echo bar; } > p

(You could also put the commands in a function and use redirection when calling the function.)

b)

exec 3>p
echo -n foo >&3
echo bar    >&3
exec 3>&-         # to explicitly close it

If you want to fix it on the reading side, you'll need to loop over read and concatenate the strings you get. Since you explicitly want partial non-lines, and to skip over end-of-file conditions, you can't use the exit code of read for anything useful.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.