将结构体作为字符缓冲区传递给进程项

Passing a structure as a char buffer to a proc entry

本文关键字:进程 缓冲区 结构体 字符      更新时间:2023-10-16

我想从程序中传递一个字符缓冲区给程序项(例如/proc/my_file)。这个字符缓冲区包含我的结构体的元素,其形式为:

struct my_table { char src_ip[4]; char dest_ip[4]; int out_flag; }my_t;

我将my_table的元素赋值并将其内容复制到unsigned char缓冲区中,如下所示:

memcpy(buffer, &my_t, sizeof(struct my_table));

然后我将缓冲区的内容写入由我创建的进程项中(名称为my_file),如下:

write(fd, buffer, sizeof(buffer));

其中fd是open()打开带有O_WRONLY | O_APPEND标志的/proc/my_file后返回的文件描述符。

我不能理解的是,我只能看到第一个字符串,即my_t。Src_ip在本例中写入/proc/my_file (did a

)
猫/proc/my_file

检查写入的内容),随后我观察到对/proc/my_file的write()操作一旦在缓冲区内容中遇到空字符就会结束。

我能知道为什么会发生这种情况以及如何解决将结构的内容写入/proc条目的问题吗?

编辑:SSCCE为我的问题:结构:

struct my_iptable { 
    char protocol[5];                   // to check whether the protocol mentioned is tcp/udp/icmp 
    char src_ip[16];                    // source ip address
    char dest_ip[16];                   // destination ip address
    char src_net_mask[16];              // source net mask
    char dest_net_mask[16];             // destination net mask
    int src_port;                       // source port number
    int dest_port;                      // destination port number
    char action[8];                     // either block or unblock
    int delete_rule;                    // gets the rule number to be deleted
    int print_flag;                     // is set if we are asked to print the rules that have been set         
    int out_flag;                       // is set if the packet is outbound, else set to 0;
};
my_ipt赋值给null:

struct my_iptable;Memset (& my_ippt, '', sizeof(struct my_iptable));

我已经正确地分配了my_ipt的字段。

向缓冲区复制和向进程写入部分:

unsigned char write_buf[sizeof(struct my_iptable)];     
    memcpy(write_buf, &my_ipt, sizeof(struct my_iptable));
int proc_fp = open("/proc/minifw", O_WRONLY | O_APPEND);
    if(proc_fp < 0) {
        printf("Couldn't open /proc/minifw for writingn");
        exit(EXIT_FAILURE);}
   if(write(proc_fp, write_buf, sizeof(struct my_iptable)) == -1) {
        printf("There was an error writing to minifw buffern");
        exit(EXIT_FAILURE);
    }
我希望这能给你我想了解的适当信息。

谢谢!

sizeof(struct my_table)代替

write(fd, buffer, sizeof(struct my_table));

如果您的buffer被定义为指针:

struct my_table *buffer;

buffer的大小将等于指针的大小(32位系统为4,64位系统为8),而不是struct my_table的实际大小