Re: Prevent a process from opening a file more than once

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

 





On Wed, Sep 28, 2011 at 11:11 AM, Michael Blizek <michi1@xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx> wrote:
Hi!

On 21:41 Tue 27 Sep     , Venkatram Tummala wrote:
> On Tue, Sep 27, 2011 at 9:19 PM, rohan puri <rohan.puri15@xxxxxxxxx> 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) {
Instead of pid check, AFAIK here tgid comparison should be done. Threads in a single process may have different pid but same tgid and we want to restrict access to only one thread in a single process. Right?
                       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


_______________________________________________
Kernelnewbies mailing list
Kernelnewbies@xxxxxxxxxxxxxxxxx
http://lists.kernelnewbies.org/mailman/listinfo/kernelnewbies

[Index of Archives]     [Newbies FAQ]     [Linux Kernel Mentors]     [Linux Kernel Development]     [IETF Annouce]     [Git]     [Networking]     [Security]     [Bugtraq]     [Yosemite]     [MIPS Linux]     [ARM Linux]     [Linux RAID]     [Linux SCSI]     [Linux ACPI]
  Powered by Linux