2013-03-28 56 views
0

我想從我的程序中將字符緩衝區傳遞給proc條目(比如/ proc/my_file)。這個字符緩衝區包含我的結構的元素它的形式是:將結構作爲char緩衝區傳遞給proc條目

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

我給你的MY_TABLE元素和它的內容複製到一個無符號字符緩衝區如下:

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

然後我寫的緩衝區內容爲我創建一個proc入口(由名字my_file)爲:

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

其中fd是)打開的/ proc/my_file無線後打開返回的文件描述符(第O_WRONLY | O_APPEND標誌。

什麼我不明白的是,我只能看到第一個字符串即my_t.src_ip在這種情況下,要寫入的/ proc/my_file(做了一個

執行cat/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到空的分配:

結構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); 
    } 

我希望這給你什麼我想明白了適當的信息。

謝謝!

+0

不是'直接寫'(fd,&my_t,sizeof(struct my_table)')?.. –

+0

嗨@xtofpernaud,我也這樣做,但無法得到我的預期。 此外,我已經宣佈我的緩衝區爲無符號字符緩衝區[sizeof(struct my_table)] – freax

+0

我想你需要產生一個[SSCCE](http://sscce.org/),如果你想要更具體的答案題。 – Sebivor

回答

3

使用sizeof(struct my_table)代替

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

如果buffer被定義爲指針:

struct my_table *buffer; 

然後buffer大小將等於指針(4的尺寸爲32位系統和8 for 64-bit systems)而不是真實大小的struct my_table

+0

能夠在沒有*緩衝區的情況下進行編程會很高興......「」擦亮你的鞋子,guvnah?「 – Sebivor

+0

@modifiablelvalue我不明白你的答案,但如果你正在處理OP,然後把你對他的問題的評論 – MOHAMED