Prevent a process from opening a file more than once

Michael Blizek michi1 at michaelblizek.twilightparadox.com
Wed Sep 28 01:41:34 EDT 2011


Hi!

On 21:41 Tue 27 Sep     , Venkatram Tummala wrote:
> On Tue, Sep 27, 2011 at 9:19 PM, rohan puri <rohan.puri15 at gmail.com> wrote:
...
> > in device_open() ->
> >
> > if(var)
> >       return -EBUSY
> > var++
> >
> > &
> >
> > in device_release() ->
> >
> > var--
> >
> >
> > I think this should do the job.
> >
> This will prevent other processes to open the file until a process releases
> it. This is not what i need. Only the threads in a process shouldn't be able
> to open the file if it is already opened in the process. Other processes
> should be able to open it.

You could create something like this:

DEFINE_MUTEX(pidlist_lock);
LIST_HEAD(pidlist);

struct pidlist_node{
	struct list_head lh;
	pid_t pid;
}

static struct pidlist_node *get_pin(void)
{
	struct list_head *curr = pidlist.next;
	while (curr != pidlist) {
		struct struct pidlist_node *pin = container_of(curr, struct pidlist_node, lh);
		if (pin->pid == current->pid) {
			return pin;
		}
	}
	return 0;
}

int open(void)
{
	struct pidlist_node *pin;

	mutex_lock(&pidlist_lock);

	pin = get_pin();
	if (pin != 0) {
		mutex_unlock(&pidlist_lock);
		return -EBUSY;
	}

	pin = kmalloc(sizeof(struct pidlist_node), GFP_KERNEL);
	if (pin == 0) {
		mutex_unlock(&pidlist_lock);
		return -ENOMEM;
	}

	pin->pid = current->pid;
	list_add(&(pin->lh), &pidlist);

	mutex_unlock(&pidlist_lock);
}

int close(void)
{
	struct pidlist_node *pin;

	mutex_lock(&pidlist_lock);

	pin = get_pin();
	if (pin != 0) {
		list_del(&(pin->lh));
		kfree(pin);
	}

	mutex_unlock(&pidlist_lock);
}

	-Michi
-- 
programing a layer 3+4 network protocol for mesh networks
see http://michaelblizek.twilightparadox.com




More information about the Kernelnewbies mailing list