Alex Rivera | Logout

clear buffer cache on Mac OS X

Asked 2009-01-19T22:58:58.947
15

Is there a way to programatically clear the buffer cache on the Mac, preferrably in C?

Basically, I'm looking for the equivalent of the source of 10.5 (and greater)'s purge command. EDIT: I now see this is part of the CHUD tools, for which it seems the source isn't directly available. However, I'm still looking for some code to do the same.

Edit
Report

2 Answers

4

Wouldn't you be interested in turning off the cache for a file instead? Depending on what you are trying to achieve, it could be an alternative. Good summary here.

UBC can be cleared by running 'purge' which allocates a lot of memory to force the cache to clear.

fcntl(fd, F_GLOBAL_NOCACHE, 1)  

can be used turn caching off for a particular file. This can be done in any process and the file can be closed after.

answered 2009-02-07T18:20:52.910
2

When you don't have the source code for the tool you wish to emulate (as is the case here), there are a number of ways to go about it.

1/ From your C code, simply call the tool with a system() function call. This works well as long as there's no visible effect (such as opening a graphical window). You could use system("/path/to/purge -purgargs >/dev/null 2>&1");, for example.

2/ Reverse-engineer the code to see how it's actually doing it. This is somewhat trickier since it will require knowledge of the assembler language, system calls and many other things.

3/ Contact the developers to obtain tips on how it was done. This doesn't have to be a "send me the code so I can rip it off and make money" question. You could phrase it as "I have an interest in using purge for development but I'm unsure exactly what is does" or "I have security issues with running the code, the powers that be won't let me run it unless we know exactly what it does". Then you code yours to do the same.

Me, I would just use option 1 if possible (I'm inherently lazy :-). If you're going to write a tool to compete with purge (and this'll be hard given it's free), option 2 is probably the best bet.

answered 2009-02-06T02:16:09.070

Your Answer