linux C使用strerror來追查錯誤信息
阿新 • • 發佈:2017-10-20
from turn log 一個 doc cal 用兩個 str sprint
最近工作中有個需求:程序將文件進行處理,然後將處理完畢的文件挪走。我用了rename函數來挪動文件,可是在docker化的環境中,文件卻無法挪動。不知道什麽原因。現在,對程序進行調整,如果rename來挪動文件失敗,那麽打印錯誤信息,同時使用另外一個辦法將其挪走。以下是簡化後的代碼。
這個程序演示了rename(),strerror(),system()函數的用法。
備考:
#include <stdlib.h> #include <stdio.h> #include <errno.h> int main(int argc, char ** argv) { printf("process begin at [%p]\n", (void *)&main); if(argc != 3) { printf("parameter error! \n usage: \t %s old_fileName new_fileName\n", argv[0]); return 1; } extern int errno; if(rename(argv[1], argv[2])) { printf("%s:%s:%d:|errno is [%d] msg is [%s]\n",__FILE__, __FUNCTION__,__LINE__,errno, strerror(errno)); char cmd[1000] = {0}; sprintf(cmd,"%s %s %s", "mv",argv[1], argv[2]); system(cmd); } else { printf("%s:%s:%d:|mv: from [%s] to [%s] ok\n",__FILE__, __FUNCTION__,__LINE__,argv[1], argv[2]); } return 0; }
正常的程序,打印的日誌為:
process begin at [0x4006b0]
renamefile.c:main:27:|mv: from [renametest] to [renametest2] ok
docker化的程序,打印的日誌為:
fileRename|DCCalcFmtBase.cpp|errno is [18] msg is [Invalid cross-device link]
docker化的程序,就算有上面的錯誤提示,也會使用system函數,去調用mv將文件挪走。
上面的日誌,實際上,我是用兩個程序去測試得到的不同的分支的提示。
linux C使用strerror來追查錯誤信息