Archive

Archive for the ‘Programming’ Category

Change Unix File Permissions Using C

March 26, 2011 Leave a comment

This is a small program written in C used to change permissions of files in Unix.

You may ask why would someone want to use a C snippet instead of a quick “chmod” shell script?

Well, a simple “chown” script works just fine for cases where you don’t have a ridiculously large amount of files. Things get painfully slow when besides having millions of files you also have millions of directories. In those rare cases there is nothing faster than C.

If you have a 64 bit operating system you can compile this code with “-m64” flag for better performance.

#include
#include
#include
#include

#define PATH "/export/home/egloo"
#define UID 501
#define GID 501
#define NOTIFICATION_INTERVAL 10000

int file_count = 0;
char cmd[128];

static int callback(const char *fpath, const struct stat *sb, int typeflag) {
// Check if it's a file or a directory
if (typeflag == FTW_D || typeflag == FTW_F) {

// Apply new permissions
chown(fpath, UID, GID);

// Send progress notification
file_count++;
if ( 0 == ( file_count % NOTIFICATION_INTERVAL ) ){
fprintf( stderr, "%ld\n", file_count );
sprintf(cmd,"/bin/echo \"%i files processed\" | /bin/mail -s \"CHOWN PROGRESS\" user@domain.com", file_count);
system(cmd);
}
}

// Continue FTW
return 0;
}

int main(int argc, char **argv) {
ftw(PATH, callback, 256);
}

Advertisements

Path of the Linux Jedi

October 17, 2008 1 comment

If you really want to get your hands on the “dirty job” and become a serious Linux programmer, I really recommend you to read the following book.

It’s called Advanced Linux Programming and is distributed under the GNU General Public License so you’re free to copy, share, and most important: read it.

BROWSE PDF FILES

As the publisher says, this book will help you to:

Develop GNU/Linux software that works the way users expect it to.
Write more sophisticated programs with features such as multiprocessing, multi-threading, interprocess communication, and interaction with hardware devices.
Improve your programs by making them run faster, more reliably, and more securely.
Understand the preculiarities of a GNU/Linux system, including its limitations, special capabilities, and conventions.

If you’re a developer already experienced with programming for the GNU/Linux system, are experienced with another UNIX-like system and are interested in developing GNU/Linux software, or want to make the transition for a non-UNIX environment and are already familiar with the general principles of writing good software, this book is for you. In addition, you will find that this book is equally applicable to C and C++ programming. Even those progamming in other languages will find this book useful since the C language APIs and conventions are the lingua franca of GNU/Linux.

As an advice, you will need a solid grasp of C programming knowledge.

Thruth be told, good luck.