[英]Can't add an array with data to shared memory
我正在嘗試將包含數據的文件寫入共享內存段。 但是,我嘗試過的一切似乎都給錯誤Segmentation錯誤。 有一天我一直在互聯網上尋求幫助。
int main(int argc, char *argv[]).
{
int sm;
char *data;
int pid=atoi(argv[1]);
int key=atoi(argv[2]);
char (*d)[1025];
data=(char*) malloc(1025);
//put the data in the shared memory segment
FILE *file=fopen(argv[3], "r"); //r for read
if (file==0)
{printf("Could not open file");}
else
{
while(fgets(data, 1025, file)!=NULL)
{
fputs(data, file);
// puts(d);
}
fclose(file);
}
//access shared memory
//S_IWUSR gives owner the write permession
sm = shmget(key, 1024, S_IWUSR);
//create a pointer to the shared memory segment
d = shmat(sm, (void *)0, 0); //shared memory id, shmaddr, shmflg
//for (int j=0; j<100; j++)
strcpy(d[0], data);
shmdt(d); //detach the shared memory segment
//remove the shared memory segment
shmctl(sm, IPC_RMID, NULL);
}
任何幫助將不勝感激預先感謝
編輯:添加了malloc
EDIT2:也許我應該改寫我的問題,我的問題是將數據放入共享內存
將其更改為rw+
,它將以讀/寫模式打開文件。 如果文件不可用,將創建它。
fputs(data, file);
在這里,文件以只讀模式打開,但是正在寫入。
但是我不確定,為什么要嘗試將讀取的數據寫入同一文件。 您應該首先考慮您的設計。
2. char(* d)[1025]; 是指向大小為1025的char數組的指針。您在strcpy()中使用它。
3.應該為data
靜態或動態分配內存。
+1關於rjayavrp答案
而且我可以添加未分配的數據...這只是一個指針,而不是字符數組。
而且你打算做什么
char (*d)[1025];
一個簡單而骯臟的例子:
#include <stdio.h>
#include <stdlib.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#define SIZE_SHARED_MEMORY 1024
int main(int argc, char *argv[])
{
int sm = -1;
char *d = NULL;
FILE *file = NULL;
key_t key = 0;
int ret = 0;
if (argc != 4)
{
return 1;
}
key = atoi(argv[2]);
//access shared memory
sm = shmget(key, SIZE_SHARED_MEMORY, IPC_CREAT | 0600);
if (sm == -1)
{
perror("shmget : Failed");
return 2;
}
//create a pointer to the shared memory segment
d = shmat(sm, (char *)0, 0);
if (d == (void *)-1)
{
perror("shmat : Failed");
return 3;
}
// Open the file
file = fopen(argv[3], "r");
if (file == NULL)
{
perror("fopen : Failed");
ret = 4;
}
else
{
if(fgets(d, SIZE_SHARED_MEMORY, file) == NULL)
{
perror("fgets : Failed");
ret = 5;
}
fclose(file);
}
shmdt(d); //detach the shared memory segment
// remove the shared memory segment ???
// Don't understand why you are doing this
shmctl(sm, IPC_RMID, NULL);
return ret;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.