[英]Passing a structure as a char buffer to a proc entry
我想從程序中將字符緩沖區傳遞給proc條目(例如/ proc / my_file)。 此字符緩沖區包含我的結構元素,其形式為:
struct my_table { char src_ip[4]; char dest_ip[4]; int out_flag; }my_t;
我分配my_table的元素,並將其內容復制到未簽名的char緩沖區,如下所示:
memcpy(buffer, &my_t, sizeof(struct my_table));
然后,我將緩沖區的內容寫入由我創建的proc條目(名稱為my_file)中,如下所示:
write(fd, buffer, sizeof(buffer));
其中fd是用O_WRONLY打開/ proc / my_file后,open()返回的文件描述符。 O_APPEND標志。
我無法理解的是,在這種情況下,我只能看到第一個字符串即my_t.src_ip寫入/ proc / my_file(沒有
貓/ 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 my_ipt; memset(&my_ipt,'\\ 0',sizeof(struct my_iptable));
我已經正確分配了my_ipt的字段。
復制到緩沖區並寫入proc部分:
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 writing\n");
exit(EXIT_FAILURE);}
if(write(proc_fp, write_buf, sizeof(struct my_iptable)) == -1) {
printf("There was an error writing to minifw buffer\n");
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
的實際大小
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.