我需要一些有关此代码的帮助。
我在共享段中创建了一个struct msg_t
,并在另一个段中创建了一个简单的字符串
。
在此方法中,首先附加两个段,然后要初始化字符串。
然后我尝试将指向该字符串的指针(在第二段中分配)写入我的 struct msg_t 的字段(在我的第一段中)。我做了很多测试,但似乎当我尝试打印从第一个段访问的该字段的内容时,它会打印“”。
我该怎么做?感谢您的帮助。
msg_t* msg_init_string(void* content) {
//viene creata una copia "privata" della stringa
msg_t* new_msg;
int new_msg_id;
int content_id;
char* string = (char*) content;
if ((new_msg_id = shmget(ftok(FILENAME2,'N'),sizeof(msg_t),IPC_CREAT|0666)) == -1) {
perror("shmget() for array_msg");
exit(-1);
}
if ((content_id = shmget(ftok(FILENAME2,'C'),(strlen(string) + 1),IPC_CREAT|0666)) == -1) {
perror("shmget() for array_msg");
exit(-1);
}
new_msg = (msg_t*)shmat(new_msg_id, NULL,0);
char* new_content =(char*)shmat(content_id,NULL,0);// +1 per \0 finale
strcpy(new_content, string);
printf("here \n %s",(char*)(new_content));
//here it seems not working..because then, it can not print anything!!
new_msg->content =new_content;
printf("here \n %s",(char*)(new_msg->content));
return new_msg;
我的简单struct msg_t
是:
typedef struct msg {
void* content; // generico contenuto del messaggio
struct msg * (*msg_init)(void*); // creazione msg
void (*msg_destroy)(struct msg *); // deallocazione msg
struct msg * (*msg_copy)(struct msg *); // creazione/copia msg
} msg_t;
最佳答案
可能您只是看不到第二个 printf()
为 %s
打印的内容,因为输出是行缓冲并且仅显示将另一个 \n
放入 stdout
后。只要可行,最好以 \n
结束格式字符串。
关于c - 共享内存段 shmget shmat 双访问两者,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20445021/