對(duì)系統(tǒng)調(diào)用的返回值進(jìn)行判斷
繼續(xù)上一條,對(duì)于一些系統(tǒng)調(diào)用,比如打開(kāi)文件,經(jīng)常有這種情況,許多程序員對(duì)fopen返回的指針不做任何判斷,就直接使用了。然后發(fā)現(xiàn)文件的內(nèi)容怎么也讀出不,或是怎么也寫(xiě)不進(jìn)去。還是判斷一下吧:
fp = fopen("log.txt", "a");
if ( fp == NULL ){
printf("Error: open file error\n");
return FALSE;
}
其它還有許多,比如:socket返回的socket號(hào),malloc返回的內(nèi)存等等。我的建議是:只要是函數(shù)聲明時(shí)返回值不是void類(lèi)型,就請(qǐng)對(duì)這些系統(tǒng)調(diào)用返回的東東進(jìn)行判斷,舉一個(gè)最常見(jiàn)的函數(shù):close,它是這么定義的:
int close(int fd);
再看一下它的一些描述:“Not checking the return value of close is a common but nevertheless serious programming error. It is quite possible that errors on a previous write operation are first reported at the final close. Not checking the return value when closing the file may lead to silent loss of data. This can especially be observed with NFS and disk quotas.”因?yàn)楝F(xiàn)代的操作系統(tǒng)都啟用了延時(shí)寫(xiě)技術(shù),在你調(diào)用write之后并不一定馬上就將數(shù)據(jù)寫(xiě)入磁盤(pán),所以close的時(shí)候有可能此時(shí)系統(tǒng)真正向磁盤(pán)寫(xiě)入大段數(shù)據(jù)導(dǎo)致close失敗。而你缺認(rèn)為文件已被關(guān)閉。解決的方法是判斷close的返回值,失敗后稍等一會(huì)兒,或是使用其他策略。