当前位置: 技术问答>linux和unix
linux 网络编程,共享内存,文件
来源: 互联网 发布时间:2016-04-10
本文导语: 有一文件txt,内有数据,如何用shared memory 将文件中的数据读出? 请用代码明示! | 本帖最后由 x86 于 2008-09-02 12:00:34 编辑 代码a.c,读文件(这部分代码略,直接用字符串data),然后写入共...
有一文件txt,内有数据,如何用shared memory 将文件中的数据读出?
请用代码明示!
请用代码明示!
|
#include
#include
#include
#include
#include
#include
#include
#include
int main(int argc, char* argv[]) {
key_t key = ftok("/tmp/1.txt", 0);
int id;
char *shared;
char data[16] = "hello, world!";
if((id = shmget(key, sizeof(int), IPC_CREAT)) == -1) {
perror("Failed to create shared memory segment");
exit(1);
}
printf("id=%dn", id);
if((shared = (char*)shmat(id, NULL, 0)) == (void*)-1){
perror("Failed to attach");
exit(1);
}
strncpy(shared, data, sizeof(data));
sleep(100);
shmdt(shared);
shmctl(id, IPC_RMID, NULL);
}
代码b.c,读共享内存。
#include
#include
#include
#include
#include
#include
#include
#include
int main(int argc, char* argv[]) {
key_t key = ftok("/tmp/1.txt", 0);
int id;
char *shared;
char data[16] = "xxxxxxxxxx";
if((id = shmget(key, sizeof(int), IPC_CREAT)) == -1) {
perror("Failed to create shared memory segment");
exit(1);
}
printf("id=%dn", id);
if((shared = (char*)shmat(id, NULL, 0)) == (void*)-1){
perror("Failed to attach");
exit(1);
}
strncpy(data, shared, sizeof(data));
printf("READ:%sn", data);
shmdt(shared);
}