通过用户空间写入/ proc条目

时间:2012-03-25 18:53:42

标签: c linux-kernel

我通过以下程序通过用户空间写入/ proc / tx_info:

int main()
{
char *prot;
char addr[14];
FILE *fp;
int i = 0; 
prot = (char *)malloc(sizeof(char *));
//addr = (char *)malloc(sizeof(char *));
printf("\n enter the protocol for test\n");
scanf(" %s",prot);
printf("\n enter the addr::");
scanf(" %s",addr);

fp =fopen("/proc/tx_info","w");
if(fp == NULL)
{
printf("\n unable to write on /proc/tx_info \n");
}
fprintf(fp,"%s ",prot);
while(addr[i] != '\0')
{
fprintf(fp,"%c",addr[i]);
i++;
}
fclose(fp);

并有一个proc读写程序如下

char tx_buffer[100];
char tx_buffer[100];
static int proc_max_size = 100;
static unsigned long buffer_size =0;


int proc_read(char *buffer,char **buffer_location,off_t offset,int buffer_length,int *eof,void *data)
{
int ret;
if(offset>0)
  {
    ret=0;
   } else {
  memcpy(buffer,tx_buffer,buffer_size);
    ret = buffer_size;
   }

            return ret;
}

int proc_write(struct file *filp, const char *buffer, unsigned long count, void *data)
{

    if(count > proc_max_size)
          count = proc_max_size;
    if(copy_from_user(tx_buffer,buffer,count))
            return -EFAULT;
//      tx_buffer[count] = '\0';
     buffer_size = count;
    return count;
}

我的i / p到prog是tcp 192.137.190.187 我做cat / proc / tx_info让我关注o / p:

tcp192.137.190.18

为什么ip地址的最后一位数字不打印

2 个答案:

答案 0 :(得分:2)

您只需为地址数组分配14个字符。您可能需要15加上null终止符,因此您应该分配16个字符。

换句话说,如果在打印之前数组并且它正在被破坏,那么你正在写完结尾。您通过写过数组的末尾来调用未定义的行为。

答案 1 :(得分:1)

addr 数组需要16个元素。最后一个元素是保存终止字符串的null。