joz*_*yqk 8 bash lsof named-pipes
我为其他进程写入了一个命名管道,并希望检查其他进程是否正确启动,但是不知道它的PID.上下文在屏幕上运行命令,确保命令正确启动.我希望这可行:
mkfifo /tmp/foo
echo hello > /tmp/foo &
lsof /tmp/foo
Run Code Online (Sandbox Code Playgroud)
可悲的是,lsof
没有报道echo
.inotifywait
可能是另一个选项,但并不总是安装,我真的只想轮询一次,而不是阻止直到某个事件.
有没有办法检查命名管道是否打开写入?一般都开放吗?
更新:
一旦两端连接lsof
似乎工作.这实际上解决了我的问题,但是为了这个问题,我有兴趣知道是否有可能在没有阅读器的情况下检测到命名管道的初始重定向.
> mkfifo /tmp/foo
> yes > /tmp/foo &
> lsof /tmp/foo
> cat /tmp/foo > /dev/null &
> lsof /tmp/foo
COMMAND PID USER FD TYPE DEVICE SIZE/OFF NODE NAME
yes 16915 user 1w FIFO 8,18 0t0 16660270 /tmp/foo
cat 16950 user 3r FIFO 8,18 0t0 16660270 /tmp/foo
Run Code Online (Sandbox Code Playgroud)
更新 2:在使用 inotify-tools 之后,似乎没有办法获得命名管道已打开用于写入并且正在阻塞的通知。这可能就是为什么lsof
在管道有读取器和写入器之前不显示管道的原因。
更新:在研究命名管道后,我不相信有任何方法可以单独使用命名管道。推理:
您可以尝试在短时间内不向管道写入任何内容。如果超时到期,则写入被阻塞,表明有人已经打开管道进行写入。
注意:正如评论中所指出的,如果读者存在并且可能足够快,我们的测试写入不会阻塞并且测试基本上失败。注释掉cat
下面的行来测试这个。
#!/bin/bash
is_named_pipe_already_opened_for_writing() {
local named_pipe="$1"
# Make sure it's a named pipe
if ! [ -p "$named_pipe" ]; then
return 1
fi
# Try to write zero bytes in the background
echo -n > "$named_pipe" &
pid=$!
# Wait a short amount of time
sleep 0.1
# Kill the background process. If kill succeeds, then
# the write was blocked indicating that someone
# else is already writing to the named pipe.
kill $pid 2>/dev/null
}
PIPE=/tmp/foo
# Ignore any bash messages from killing below
trap : TERM
mkfifo $PIPE
# a writer
yes > $PIPE &
# a reader
cat $PIPE >/dev/null &
if is_named_pipe_already_opened_for_writing "$PIPE"; then
echo "$PIPE is already being written to by another process"
else
echo "$PIPE is NOT being written to by another process"
fi
jobs -pr | kill 2>/dev/null
rm -f $PIPE
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
2325 次 |
最近记录: |