PDA

View Full Version : Can a C program listen?




farmerdoug
Apr 6, 2011, 12:55 PM
Normally if you want to know if something has happened, your c program has to ask, usually in a loop. Can I do this the other way? If, for example a file appears or a usb port is used, can the c program be told without asking. I'm trying to limit use of the computers resources.



lee1210
Apr 6, 2011, 01:20 PM
It depends on what the thing is. Generally in UNIX everything is a file. As such, there is a function "select" that lets you wait for something to change about a file. Is it ready to read? Read to write? etc. Whether that's actually a network socket, a real file, a pipe, etc. you treat them the same. Lookup "select" to see if it will suit your needs. For "system events" like a USB drive being plugged in this may not fit the bill.

-Lee

Sydde
Apr 6, 2011, 01:22 PM
You also might want to look at kqueues and kevents (http://www.manpagez.com/man/2/kqueue/)

chown33
Apr 6, 2011, 03:17 PM
Be specific about what you want to listen for.

There are much simpler ways of listening for some things than kqueues or select(). It's called launchd. You tell it what things to listen for: a change to a directory, a request to establish a socket, a certain time or day, etc. It then runs your program when that event occurs. Your program doesn't run at all unless and until the event occurs. And launchd is a boot process, so it's always running anyway, whether you're using its services or not.

You configure launchd through plists, so you may not even have to write any code. You might be able to use an existing tool, or a simple shell script, that's run when the event occurs.

Not every possible event or condition can be triggered through launchd, but for those that can, it's a huge savings of time and effort.

man launchd.plist

TN2083:
http://developer.apple.com/mac/library/technotes/tn2005/tn2083.html

balamw
Apr 6, 2011, 03:34 PM
It depends on what the thing is.

Be specific about what you want to listen for.


It also depends somewhat on how often you want to check for these events and whether the events are transitory or longer lasting state shifts.

In the case of a file appearing. Does your task need to happen immediately after the file appears? Can it wait a minute, 5 minutes, 10 minutes? Is there any chance the file will disappear before you can act on it? ...

B

farmerdoug
Apr 7, 2011, 08:34 AM
thanks Lee. I'll look into it.