问题
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