Ruby 在bash中打开命名管道,而不读取或写入
我想在bash中使用一个命名管道,而无需对其进行读写,直到事件发生。我需要在shell脚本运行的整个过程中保持此管道打开。我会在需要的时候阅读它。也就是说,可以这样做:Ruby 在bash中打开命名管道,而不读取或写入,ruby,linux,bash,shell,named-pipes,Ruby,Linux,Bash,Shell,Named Pipes,我想在bash中使用一个命名管道,而无需对其进行读写,直到事件发生。我需要在shell脚本运行的整个过程中保持此管道打开。我会在需要的时候阅读它。也就是说,可以这样做: open(<$NAMED_PIPE>, "r+") --do something-- --call child ruby script, which will write to named pipe-- --do something more--- read line < $NAMED_PIPE 以及try2
open(<$NAMED_PIPE>, "r+")
--do something--
--call child ruby script, which will write to named pipe--
--do something more---
read line < $NAMED_PIPE
以及try2.sh脚本(称为ruby脚本):
#/垃圾箱/垃圾箱
mkfifomypipe
执行官4阅读第行在没有关于脚本如何使用管道权限的信息的情况下,我可以想到一个可能的选项
1) 开放管道mkfifo/path/to/pipe
2) 做点什么echo test1
3) 调用子ruby脚本,它将写入命名管道(假设脚本是可执行的)/path/to/script>/path/to/pipe&
4) 执行更多操作echo test2
5) 从管道读取行读取管道数据
使用Bash非常简单:
# Open the named pipe with a custom fd for input
exec 4< /path/to/named_pipe
# Do other things
:
# Read a line from pipe
read -ru 4 line
# Or
read -r line <&4
# Just make this consistent and close it when you're done. May not be necessary at exit but still a good practice.
exec 4<&-
额外好处:您还可以在块范围内打开命名管道,如{}
,while
,for
,if
,till
等。。使用时,无需关闭文件描述符:
{
# Do reads and other things
...
} 4< /path/to/named_pipe
{
#做阅读和其他事情
...
}4
@Nehal我已经搜索了一个解决方案堆栈溢出和google,但没有找到满意的答案,所以在这里特别询问…@YusufHusainy在运行exec
打开命名管道之前,你应该先调用你的ruby脚本(很可能是在后台)。当然,打开命名管道会阻止任何这样做的进程。而且我不记得您可以打开命名管道进行读写。您只需在一端执行读取或写入操作:w+
inoutput=open(“mypipe”、“w+”)
中的w
@konsolebox就可以了。是的,这对我有用,非常感谢。w+用于告诉ruby我们是非阻塞写。参考这个[链接]:我不确定这是否正确。看。或者你指的是一个不同的开放?顺便说一句,欢迎。
[yusufh@verigybuild6 Ruby]$ bash -xv try2.sh --cpl on &
[1] 2777
[yusufh@verigybuild6 Ruby]$ #!/bin/sh
mkfifo mypipe
+ mkfifo mypipe
exec 4< /home/yusufh/Ruby/mypipe
+ exec
[yusufh@verigybuild6 Ruby]$ echo "Hello World" > mypipe
[yusufh@verigybuild6 Ruby]$
OPT=$*
+ OPT='--cpl on'
./try1.rb ${OPT}
+ ./try1.rb --cpl on
Hello World!, This is my first ruby program
on
#read -ru 4 line
read line <&4
+ read line
echo $line
+ echo Hello World
Hello World
exec 4<&- #close FIFO my_pipe
+ exec
rm mypipe
+ rm mypipe
[1]+ Done bash -xv try2.sh --cpl on
[yusufh@verigybuild6 Ruby]$
# Open the named pipe with a custom fd for input
exec 4< /path/to/named_pipe
# Do other things
:
# Read a line from pipe
read -ru 4 line
# Or
read -r line <&4
# Just make this consistent and close it when you're done. May not be necessary at exit but still a good practice.
exec 4<&-
exec 4> /path/to/named_pipe
echo something >&4
exec 4>&-
{
# Do reads and other things
...
} 4< /path/to/named_pipe