linux驱动学习之旗标的使用

     下面简单介绍一下旗标的使用,介绍如何在任何时间只有一个执行线程可以操作一个共享资源,首先介绍一下模型,首先用c写一个测试应用创建5个进程去打开一个设备,没加旗帜时5个进程同时打开使用完后关闭,加了旗帜后每次只能打开一个,其他进程等待设备使用完后才能操作,模板使用上次介绍的模板。


测试c代码,创建5个进程打开同时打开设备

#include <stdio.h>
#include <fcntl.h>
#include <sys/types.h>
#include <unistd.h>
int main (int *argc,char**argv)
{
  pid_t  pid;
  int  fs,i;
  for(i=0;i<5;i++)
  {
    pid=fork();
    if(pid<0)
    {
      printf("fork error!\n");
	  return -1;  
    }
    else if(pid==0)
    {
      /*子进程使用设备*/
      fs=open("/dev/moduledev60",O_RDWR);
      if(fs<0)
      {
        printf("open fail\n");
        return -1;
      }
	  printf("open by pid:%d \n",getpid());
      usleep(2000);
      close(fs);
	  printf("close by pid:%d \n",getpid()); 
	  return 0;
	}  
  }
  sleep(1);
  return 0;
}

驱动修改

#include <linux/init.h>
#include <linux/kernel.h>
#include <linux/kdev_t.h>
#include <linux/err.h>
#include <linux/cdev.h>
#include <linux/fs.h>
#include "fileops.h"
#include <asm/uaccess.h>
#include <linux/delay.h>
#include "linux/semaphore.h"
struct semaphore sem;
/**
 * 初始化 在加载时候调用
 */
int fileops_init(void)
{
   sema_init(&sem,1);
   return 0;
}

/**
 *释放函数 在模块卸载时候调用
 */
void fileops_destroy(void)
{

}

int fileops_open(struct inode *inode, struct file *filp)
{
  if (down_interruptible(&sem)) return -1;
  printk(KERN_ALERT "fileops_open\n");
  return 0;   
}

int fileops_release(struct inode *inode,struct file *filp)
{
  printk(KERN_ALERT "fileops_release\n");
  up(&sem);
  return 0;
}

main.c修改

struct file_operations ops=
{
   .owner=THIS_MODULE,
   .open=fileops_open,
   .release=fileops_release
};


未加旗帜时的测试结果 设备被多个进程同时打开

[root@localhost ctest]# ./main;
open by pid:5237 
open by pid:5239 
open by pid:5235 
open by pid:5238 
open by pid:5236 
close by pid:5237 
close by pid:5239 
close by pid:5235 
close by pid:5238 
close by pid:5236 

加旗帜后的测试结果 设备逐个打开

[root@localhost ctest]# ./main;
open by pid:8618 
close by pid:8618 
open by pid:8620 
close by pid:8620 
open by pid:8617 
close by pid:8617 
open by pid:8621 
close by pid:8621 
open by pid:8619 
close by pid:8619













评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值