Re: problem in reading a file in kernel space

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

 



On 10/19/05, santosh pattar <santoshkumar_pattar@xxxxxxxxx> wrote:
> Hi,
>
> I am getting a problem when reading a file in kernel space. can any one help
> me with this.
>
>

Its better not to open files in kernel space rather get data in user
space and send it to kernel space through sysfs/netlink etc ....

>
> #include <linux/module.h>
> #include <linux/fs.h>
> #include <linux/file.h>
> #include <linux/syscalls.h>
> MODULE_LICENSE("GPL");
> static char buff[100];
> int init_module(void)
> {
>  struct file *filp;
>  int unused_fd, nbr;
>  printk("loading hello\n");
>  filp = filp_open("a.txt",O_RDWR,0);    // a.txt is a file which i need to
> read
>  unused_fd = get_unused_fd();
>  printk("unused_fd = %d\n", unused_fd);
>  fd_install(unused_fd, filp);
>  nbr = sys_read(unused_fd, buff, 100);    // problem is here. nbr returning
> error.
>  printk("nbr= %d", nbr);
>  printk( "%s", buff);
>  return 0;
> }
> void cleanup_module(void)
> {
>  printk("Unloading hello\n");
> }
>
>

I think ur code is very messy .... which is the main problem .... The
simple way u can use is like :

int file_read_func() {

  mm_segment_t old_fs;
  int err;

  char *tmp;

  struct _c4_file_struct {
	  struct file *file;
	  int pos;
	  int size;
  } fs_loader;


  old_fs = get_fs();
  set_fs(get_ds());
  tmp = getname("<file_name_and_path>");

  fs_loader.size = 0;
  fs_loader.file = filp_open(tmp, O_RDWR | O_NONBLOCK | O_CREAT, 0600);

  putname(tmp);

  if ((fs_loader.file->f_op == NULL) || (fs_loader.file->f_op->read == NULL) ||
      (fs_loader.file->f_op->write == NULL)) {
          printk("%s", "Wrong f_op or FS doesn't have required capabilities");
          res = -EINVAL;
          goto out_close_file;
  }

// Call function for read or write (below is read example) ..
  err = fs_loader.file->f_op->read(fs_loader.file,
<ur_buffer_for_read/write>,  <size_to_read>,  &fs_loader.file->f_pos);

  filp_close(fs_loader.file, current);
  fs_loader.file = NULL;
  set_fs(old_fs);

  return -1;

out_close_file:

  filp_close(fs_loader.file, current);
  fs_loader.file = NULL;
  set_fs(old_fs);

  return -1;

}

I hope this will work .....



--
Fawad Lateef

--
Kernelnewbies: Help each other learn about the Linux kernel.
Archive:       http://mail.nl.linux.org/kernelnewbies/
FAQ:           http://kernelnewbies.org/faq/



[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