简体   繁体   中英

In Linux, I'm looking for a way for one process to signal another, with blocking

I'm looking for a simple event notification system:

  1. Process A blocks until it gets notified by...

  2. Process B, which triggers Process A.

If I was doing this in Win32 I'd likely use event objects ('A' blocks, when 'B' does a SetEvent). I need something pretty quick and dirty (prefer script rather than C code). What sort of things would you suggest? I'm wondering about file advisory locks but it seems messy. One of the processes has to actively open the file in order to hold a lock.

Quick and dirty?

Then use fifo . It is a named pipe. The process A read from the fifo's FD with blocking mode. The process B writes to it when needed.

Simple, indeed.

And here is the bash scripting implementation:

Program A:

#!/bin/bash

mkfifo /tmp/event
while read -n 1 </tmp/event; do 
    echo "got message";
done

Program B:

#!/bin/bash
echo -n "G" >>/tmp/event

First start script A, then in another shell window repeatedly start script B.

除了fifo之外,您还可以使用信号和kill来进行中断,并使一个进程进入睡眠状态,直到它收到诸如SIGUSR1之类的信号,然后将其解除阻塞(您可以使用条件变量轻松实现此目的而无需轮询)。

Slow and clean?

Then use (named) semaphores: either POSIX or SysV (not recommended, but possibly slightly more portable). Process A does a sem_wait (or sem_timedwait ) and Process B calls sem_post .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM