From: Thadeu Lima de Souza Cascardo Date: Tue, 8 Dec 2009 17:58:11 +0000 (-0200) Subject: Control size of buffer. X-Git-Url: http://git.cascardo.info/?p=cascardo%2Fkernel%2Fsamples%2F02.char%2F.git;a=commitdiff_plain;h=0f97392e9082dbf08807986bad7e1a20e781a807;ds=sidebyside Control size of buffer. --- diff --git a/helloc.c b/helloc.c index f43a767..9f983a2 100644 --- a/helloc.c +++ b/helloc.c @@ -31,6 +31,14 @@ static int helloc_open(struct inode *ino, struct file *filp) return -ENODEV; msg = hello_message[iminor(ino)]; filp->private_data = msg; + if (filp->f_flags & O_TRUNC) { + memset(msg->text, 0, msg->len); + msg->len = 0; + printk(KERN_INFO "File opened with truncate flags\n"); + } + if (filp->f_flags & O_APPEND) { + filp->f_pos = msg->len; + } return 0; } @@ -67,18 +75,27 @@ static ssize_t helloc_write(struct file *filp, const char __user *buf, int r; struct message *msg = filp->private_data; /* do not read pass through the size of the message */ - if (*pos >= msg->len) + if (*pos >= BUFFER_SIZE) /* return end of file */ return 0; /* if len is bigger than the rest of the message, clamp it */ - if (len > msg->len - *pos) - len = msg->len - *pos; + if (len > BUFFER_SIZE - *pos) + len = BUFFER_SIZE - *pos; + /* copy message to user space and return error if it fails */ r = copy_from_user(msg->text + *pos, buf, len); - if (r) + if (r) { + if (*pos + len > msg->len) + memset(msg->text + msg->len, 0, *pos + len - msg->len); return -EFAULT; + } /* update the file position */ *pos += len; + if (msg->len < *pos) { + printk(KERN_DEBUG "Updating size from %d to %lld\n", msg->len, *pos); + msg->len = *pos; + } + return len; }