一向的观点就是“别在内核里面处理字符串”!事实上,确实应该如此!
Linux内核的块设备驱动有能力读取磁盘的序列号,这个数据存储在磁盘的控制芯片ROM里面。内核应该以怎样的形式将这个序列号呈现给调用者呢?我们ls一下这个目录:
/dev/disk/by-id
ll /dev/disk/by-id/static char *strip (char *s) { char *e; while (*s == ' ') ++s; if (*s) for (e = s + strlen(s); *--e == ' '; *e = '\0'); return s; } static void dump_identity (__u16 *idw) { int i; char pmodes[64] = {0,}, dmodes[128]={0,}, umodes[128]={0,}; char *model = strip(strndup((char *)&idw[27], 40)); char *fwrev = strip(strndup((char *)&idw[23], 8)); char *serno = strip(strndup((char *)&idw[10], 20)); __u8 tPIO; printf("\n Model=%.40s, FwRev=%.8s, SerialNo=%.20s", model, fwrev, serno); ... }很明显,在显示序列号时,strip去掉了首尾的空格,因为空格显示出来是没有意义的。这十分正常。然而...
void ide_fixstring (u8 *s, const int bytecount, const int byteswap) { u8 *p = s, *end = &s[bytecount & ~1]; /* bytecount must be even */ if (byteswap) { /* convert from big-endian to host byte order */ for (p = end ; p != s;) { unsigned short *pp = (unsigned short *) (p -= 2); *pp = ntohs(*pp); } } /* strip leading blanks */ while (s != end && *s == ' ') ++s; /* compress internal blanks and strip trailing blanks */ while (s != end && *s) { if (*s++ != ' ' || (s != end && *s && *s != ' ')) *p++ = *(s-1); } /* wipe out trailing garbage */ while (p != end) *p++ = '\0'; }几乎是hdparm的strip更加严格意义上的翻版!这有什么问题呢?问题大了。这个内核没有办法给用户呈现一个原始的磁盘序列号,也就是序列号本身。为何不把处理留给应用程序呢?