Become a MacRumors Supporter for $50/year with no ads, ability to filter front page stories, and private forums.

farmerdoug

macrumors 6502a
Original poster
Sep 16, 2008
541
0
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.
 
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
 
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
 
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
 
Register on MacRumors! This sidebar will go away, and you'll see fewer ads.