Linux-C从共享内存中读取数据已损坏

时间:2017-01-04 23:27:00

标签: c linux shared-memory

我从共享内存中写一个字符串。 这是我的代码:

这是作者(我有无关的代码)

int main() {

    char message[MAX_BUF];
    key_t key;
    int sharedMemoryId;
    int semaphoreId;
    char *vc1;
    char *data;
    pid_t p3;
    struct sembuf operations[1];

    printf("start p2\n");

    saveMesageInBuffer(message); //This reads message from pipe and saves into message variable

    if(message==NULL){
      return -1;
    }

    key = getKeyForFile();

    if(key != -1){

      sharedMemoryId = createSharedMemoryId(key);
      if(sharedMemoryId!=-1){
        vc1 = shareContentInMemoryId(sharedMemoryId);
      }

      switch(p3 = fork()){
        case -1: 
            printf("Error");
            break;
        case 0:
            printf("run\n");
            execl("./Ej3", "Ej3", NULL);
            break;
        default:
            sleep(SECONDS);
            writeMessageInSharedVariable(vc1, message);
            pause();
            break;
    }

    } else {
       printf("Error getting key for file: %s\n", strerror(errno));
    }

    return 0;
}

void writeMessageInSharedVariable(char *dest, char *message){
  printf("El proceso P2 (PID=%d, Ej2) transmite un mensaje al proceso P3 a traves de una variable en memoria compartida\n", getpid());
  strncpy(dest, message, MAX_BUF);
}

int createSharedMemoryId(key_t key){
  return shmget(key, MAX_BUF, IPC_CREAT | 0600);
}

char* shareContentInMemoryId(int memoryId){
  return shmat(memoryId, (void *)0, 0);
}

key_t getKeyForFile(){
  char filePath[1024];
  if (getcwd(filePath, sizeof(filePath)) != NULL){
        strcat(filePath, "/");
        strcat(filePath, FIFO_FILE_NAME);
        return ftok(filePath, 0777);
  } else {
    return (key_t) -1;
  }
}

`

这是读者(编译为Ej3并通过fork和exec从编写器启动)

int main() {
    key_t key;
    char message[MAX_BUF];
    int sharedMemoryId;
    char* vc1;

    printf("el 33 \n");

    key = getKeyForFile();
        if(key != -1){
        sharedMemoryId = createSharedMemoryId(key, sizeof(message));
        sleep(3);
        printf("continua\n");
        vc1 = (char*)shmat(sharedMemoryId, (void *)0, 0);
        if (vc1 == (char *)(-1)) {
            perror("shmat");
            exit(1);
        }
        printf("Readed %s\n", vc1);

    } else {
        printf("Error getting key for file: %s\n", strerror(errno));
    }

}

我正在写消息中的测试,这是我阅读时的结果。

Readedtest [] w

1 个答案:

答案 0 :(得分:3)

IS_TRUE("=")

strncpy doesn't null-terminate the buffer。 您必须自己将其终止。

strncpy(dest, message, MAX_BUF);

strncpy(dest, message, MAX_BUF); dest[MAX_BUF-1] = '\0'; /* <- like this */ 接受C-string,它是一个char数组,最后是一个空字符。如果你没有空终止字符串,printf(%s将不知道何时停止,因此垃圾输出。