Can a C program listen?

Discussion in 'Mac Programming' started by farmerdoug, Apr 6, 2011.

  1. macrumors 6502a

    Sep 16, 2008
    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.
  2. macrumors 68040


    Jan 10, 2005
    Dallas, TX
    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.

  3. macrumors 68000


    Aug 17, 2009
  4. macrumors 604

    Aug 9, 2009
    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

  5. Moderator


    Staff Member

    Aug 16, 2005
    New England
    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? ...

  6. thread starter macrumors 6502a

    Sep 16, 2008

Share This Page