主题 : 光盘示例程序中的led控制程序参数的疑问 复制链接 | 浏览器收藏 | 打印
级别: 新手上路
UID: 418
精华: 0
发帖: 21
金钱: 205 两
威望: 39 点
综合积分: 42 分
注册时间: 2008-03-29
最后登录: 2011-05-06
楼主  发表于: 2008-04-03 10:57

 光盘示例程序中的led控制程序参数的疑问

程序的部分代码如下:

#include ......
int main(int argc, char **argv)
{
  int on;
  int led_no;

  int fd;
  /* 检查led 控制的两个参数,如果没有参数输入则退出。*/
  if (argc != 3 || sscanf(argv[1], "%d", &led_no) != 1 || sscanf(argv[2],"%d", &on) != 1 ||
      on < 0 || on > 1 || led_no < 0 || led_no > 3) {
        fprintf(stderr, "Usage: leds led_no 0|1\n");
        exit(1);
    }
....
....
  /*通过系统调用ioctl 和输入的参数控制led*/
  ioctl(fd, on, led_no);
....
}

问题是
ioctl中的on led_no参数是怎么传递进来的啊?
*無鈳取玳
级别: 论坛版主
UID: 27
精华: 12
发帖: 5398
金钱: 40120 两
威望: 17929 点
综合积分: 11036 分
注册时间: 2008-01-16
最后登录: 2014-11-22
1楼  发表于: 2008-04-03 13:49
  /* 检查led 控制的两个参数,如果没有参数输入则退出。*/
  if (argc != 3 || sscanf(argv[1], "%d", &led_no) != 1 || sscanf(argv[2],"%d", &on) != 1 ||
      on < 0 || on > 1 || led_no < 0 || led_no > 3)

事实上这段代码并不是只检查命令行参数的个数是否为3, '||'的逻辑会让这个if语句一直判断到条件成立或者所有的判断都完成为止,即

如果argc != 3不为true, 继续执行sscanf(argv[1], "%d", &led_no) 并且判断sscanf()的返回值;
如果sscanf(argv[1], "%d", &led_no) != 1不为true, 继续执行后面的sscanf(argv[2],"%d", &on)并判断其返回值;
....一直到所有的判断全部完成。
如果每一个判断都不为true,事实上也就执行了所有的判断语句,即从命令行参数上输入了led_no和on的值。


这段代码写的很有'技巧',但不是好的编程风格。

你能提出这样的问题很好,C编程事实上有很多值得讨论的地方,希望这样的帖子在论坛上越来越多。
"If you have an apple and I have an apple and we exchange apples, then you and I will
still each have one apple. But if you have an idea and I have an idea and we exchange
these ideas, then each of us will have two ideas."
*無鈳取玳
级别: 论坛版主
UID: 27
精华: 12
发帖: 5398
金钱: 40120 两
威望: 17929 点
综合积分: 11036 分
注册时间: 2008-01-16
最后登录: 2014-11-22
2楼  发表于: 2009-10-11 17:46

 回 2楼(jj807) 的帖子

因为驱动里ioctl的处理函数就是这么定义的。ioctl是根据驱动特定的,参数的定义由驱动决定。
"If you have an apple and I have an apple and we exchange apples, then you and I will
still each have one apple. But if you have an idea and I have an idea and we exchange
these ideas, then each of us will have two ideas."
*無鈳取玳
级别: 论坛版主
UID: 27
精华: 12
发帖: 5398
金钱: 40120 两
威望: 17929 点
综合积分: 11036 分
注册时间: 2008-01-16
最后登录: 2014-11-22
3楼  发表于: 2009-10-12 11:56

 回 4楼(jj807) 的帖子

准确的说,没有标准接口的驱动程序需要运用程序跟着驱动写。
友善之臂提供的2.6.29内核中各驱动程序源代码位置在 http://www.arm9.net/mini2440-linux.asp
"If you have an apple and I have an apple and we exchange apples, then you and I will
still each have one apple. But if you have an idea and I have an idea and we exchange
these ideas, then each of us will have two ideas."