/proc 파일에 입력하는 소스인데요...
제목 그대로 /proc파일에 내용을 입력하는 소스를 한번 작성해봤는데요
/proc에 파일은 잘 생성되는데 입력이 잘 안되네요.. 메모리상에 문제가 있는거 같은데 뭐가 문제인지좀 봐주세요
부탁드립니다~
#include /* 커널 작업 */
#include /* 모듈 작업 */
#include /* /proc 파일 시스템을 이용하기 위한 헤더 */
#include /* 메모리 할당을 위한 헤더 */
#include
MODULE_LICENSE("GPL");
#define PROCFS_MAX_SIZE 128
#define PROCFS_NAME "testModule"
static struct proc_dir_entry *proc_entry; /* proc 파일 생성을 위한 구조체*/
static char *message_buf; /* proc 파일에서 사용할 버퍼 */
/* 메시지를 쓰는 함수 */
ssize_t procfile_write(struct file *filp, const char __user *buffer, unsigned long count, void *data )
{
message_buf = (char *)data;
if (count > PROCFS_MAX_SIZE) {
printk(KERN_INFO "Message Buffer is full!\n");
return -ENOSPC;
}
/* 사용자 영역에서 커널 영역으로 버퍼를 복사한다. */
if (copy_from_user( &message_buf[0], buffer, count ))
return -EFAULT;
message_buf[count] = '\0';
return count;
}
/* 메시지를 읽는 함수 */
int procfile_read( char *page, char **start, off_t off, int count, int *eof, void *data )
{
char *realdata;
char *buf;
realdata = (char *)data;
buf = page;
buf += sprintf(buf, "%s\n", realdata);
*eof = 1;
return buf - page;
}
/* Initialize the module - register the proc file */
int init_module()
{
printk(KERN_INFO "init_module() called. Module is now loaded.\n"); /* 임시 확인 */
message_buf = (char *)vmalloc(PROCFS_MAX_SIZE);/* 가상으로 연속된 메모리 블록을 할당한다. */
if (!message_buf)
return -ENOMEM;
memset(message_buf, 0, PROCFS_MAX_SIZE);
proc_entry=create_proc_entry(PROCFS_NAME, 0644, NULL);
if(proc_entry==NULL){
remove_proc_entry(PROCFS_NAME,NULL);
vfree(message_buf); /* vmalloc으로 할당한 메모리 블록을 해제한다. */
printk(KERN_ALERT "Error : Could not initialize /proc/%s\n",PROCFS_NAME);
return -ENOMEM;
}
proc_entry->read_proc=procfile_read;
proc_entry->write_proc=procfile_write;
proc_entry->owner=THIS_MODULE;
proc_entry->mode=S_IFREG | S_IRUGO | S_IWUSR;
proc_entry->uid=0;
proc_entry->gid=0;
printk(KERN_INFO "/proc/%s created\n",PROCFS_NAME); /* 임시 확인 */
return 0;
}
/* Cleanup - unregister our file from /proc */
void cleanup_module()
{
printk(KERN_INFO "cleanup_module() called. Module is now unloaded.\n"); /* 임시 확인 */
remove_proc_entry(PROCFS_NAME, NULL);
printk(KERN_INFO "/proc/%s removed\n",PROCFS_NAME); /* 임시 확인 */
vfree(message_buf);
printk(KERN_INFO "message_buf free!\n"); /* 임시 확인 */
}
어케 해결하긴 했는데 ㅡㅡ;;
메세지 쓰기 함수에서
message_buf[count] = '\0';
이거를
message_buf[count-1] = '\0';
이거로 바꾸고
메세지 읽는 함수를 아래와 같이 바꾸니까 문제없이 아주 잘되긴 하는데 제가 해결해놓고도 이유를 모르겠네요;;
/* 메시지를 읽는 함수 */
int procfile_read( char *page, char **start, off_t off, int count, int *eof, void *data )
{
int len;
len = sprintf(page, "%s\n", &message_buf[0]);
return len;
}
왜 그런 건가요??;
두번째는 잘
두번째는 잘 모르겠고 첫번째는 전형적인 off-by-one 에러 같네요.
---- 절취선 ----
http://blog.peremen.name
댓글 달기