IOCTL call and checking return value

孤人 提交于 2019-12-10 19:43:15

问题


if((err = ioctl(fd, IOC_CARD_LOCK, &lock)) < 0)
{
     printf("ioctl failed and returned errno %d \n",err);
}

Is the above code correct and a good programming practice? It does compile on my PC. i.e does it populate err with the return value of ioctl and check if err is < 0

Is the above method a standard way to return "err" returned by IOCTL.

There seem to be some standard variable called errno? what is it? Will that be the same as above?


回答1:


I found out a better way to do this.

if(ioctl(fd, IOC_CARD_LOCK, &lock) < 0)
{
     printf("ioctl failed and returned errno %s \n",strerror(errno));
}

errno is a global variable that is set for system calls.and strerror converts the code (a negative integer) into a meaningful string ("Invalid argument" for example.)




回答2:


Just stumbled over this response. The answer is only partly correct, as printf might overwrite errno - according to the man pages it's mandatory to save errno. So a more robust answer is:

if(ioctl(fd, IOC_CARD_LOCK, &lock) < 0)
{
    int errsv = errno;
    printf("ioctl failed and returned errno %s \n",strerror(errsv));
}


来源:https://stackoverflow.com/questions/14968238/ioctl-call-and-checking-return-value

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!