练习:
实现shell里面的umask命令
void get_umask(int argc,char * argv[]) { if(argc == 2)//get umask { mode_t mode = umask(0000); int user = 0,group = 0,other = 0; if(mode & S_IRUSR) user = user + 4; if(mode & S_IWUSR) user = user + 2; if(mode & S_IXUSR) user = user + 1; if(mode & S_IRGRP) group = group + 4; if(mode & S_IWGRP) group = group + 2; if(mode & S_IXGRP) group = group + 1; if(mode & S_IROTH) other = other + 4; if(mode & S_IWOTH) other = other + 2; if(mode & S_IXOTH) other = other + 1; umask(mode); printf("0%d%d%d\n",user,group,other); } else//set umask { int len = strlen(argv[2]); switch(len) { case 1: { int a; a = argv[2][0] - '0'; mode_t mode = 0; if(a < 0 || a > 7) { printf("octal number out of range\n"); return ; } if(a & 0x04) mode = mode | S_IROTH; if(a & 0x02) mode = mode | S_IWOTH; if(a & 0x01) mode = mode | S_IXOTH; umask(mode); break; } case 2: { int a,b; mode_t mode = 0; a = argv[2][0] - '0'; b = argv[2][1] - '0'; if(a < 0 || a > 7 || b < 0 || b > 7) { printf("octal number out of range\n"); return ; } if(b & 0x04) mode = mode | S_IROTH; if(b & 0x02) mode = mode | S_IWOTH; if(b & 0x01) mode = mode | S_IXOTH; if(a & 0x04) mode = mode | S_IRGRP; if(a & 0x02) mode = mode | S_IWGRP; if(a & 0x01) mode = mode | S_IXGRP; umask(mode); break; } case 3: { int a,b,c; mode_t mode = 0; a = argv[2][0]; b = argv[2][1]; c = argv[2][2]; if(a < 0 || a > 7 || b < 0 || b > 7 || c < 0 || c > 7) { printf("octal number out of range\n"); return ; } if(a & 0x04) mode = mode | S_IRUSR; if(a & 0x02) mode = mode | S_IWUSR; if(a & 0x01) mode = mode | S_IXUSR; if(b & 0x04) mode = mode | S_IRGRP; if(b & 0x02) mode = mode | S_IWGRP; if(b & 0x01) mode = mode | S_IXGRP; if(c & 0x04) mode = mode | S_IROTH; if(c & 0x02) mode = mode | S_IWOTH; if(c & 0x01) mode = mode | S_IXOTH; umask(mode); break; } default: { int a,b,c,d; mode_t mode = 0; a = argv[2][len-4]; b = argv[2][len-3]; c = argv[2][len-2]; d = argv[2][len-1]; if(a != 0 || b < 0 || b > 7 || c < 0 || c > 7 || d < 0 || d >7) { printf("octal number out of range\n"); return ; } if(b & 0x04) mode = mode | S_IRUSR; if(b & 0x02) mode = mode | S_IWUSR; if(b & 0x01) mode = mode | S_IXUSR; if(c & 0x04) mode = mode | S_IRGRP; if(c & 0x02) mode = mode | S_IWGRP; if(c & 0x01) mode = mode | S_IXGRP; if(d & 0x04) mode = mode | S_IROTH; if(d & 0x02) mode = mode | S_IWOTH; if(d & 0x01) mode = mode | S_IXOTH; umask(mode); break; } } } }
原文地址:http://blog.csdn.net/yao_wust/article/details/39255531