對系統調用的返回值進行判斷
繼續上一條,對于一些系統調用,比如打開文件,經常有這種情況,許多程序員對fopen返回的指針不做任何判斷,就直接使用了。然后發現文件的內容怎么也讀出不,或是怎么也寫不進去。還是判斷一下吧:
fp = fopen("log.txt", "a");
if ( fp == NULL ){
printf("Error: open file error\n");
return FALSE;
}
其它還有許多,比如:socket返回的socket號,malloc返回的內存等等。我的建議是:只要是函數聲明時返回值不是void類型,就請對這些系統調用返回的東東進行判斷,舉一個最常見的函數: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.”因為現代的操作系統都啟用了延時寫技術,在你調用write之后并不一定馬上就將數據寫入磁盤,所以close的時候有可能此時系統真正向磁盤寫入大段數據導致close失敗。而你缺認為文件已被關閉。解決的方法是判斷close的返回值,失敗后稍等一會兒,或是使用其他策略。