78 lines
2.6 KiB
C++
78 lines
2.6 KiB
C++
/*
|
|
* Copyright (c) 2023 Fancy Code.
|
|
* Licensed under the Apache License, Version 2.0 (the "License");
|
|
* you may not use this file except in compliance with the License.
|
|
* You may obtain a copy of the License at
|
|
*
|
|
* http://www.apache.org/licenses/LICENSE-2.0
|
|
*
|
|
* Unless required by applicable law or agreed to in writing, software
|
|
* distributed under the License is distributed on an "AS IS" BASIS,
|
|
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
* See the License for the specific language governing permissions and
|
|
* limitations under the License.
|
|
*/
|
|
#include "SharedMemory.h"
|
|
#include "ILog.h"
|
|
#include "LinuxApi.h"
|
|
#include "SharedData.h"
|
|
#include "SharedDataCode.h"
|
|
#include "StatusCode.h"
|
|
#include <errno.h>
|
|
#include <stdio.h>
|
|
#include <stdlib.h>
|
|
#include <string.h>
|
|
#include <sys/ipc.h>
|
|
#include <sys/shm.h>
|
|
#include <sys/types.h>
|
|
#include <unistd.h>
|
|
constexpr int SHMGET_FAILED = -1;
|
|
SharedMemory::SharedMemory(const char *path, const int &projectId) : mPath(path), mProjectId(projectId)
|
|
{
|
|
mId = SHMGET_FAILED;
|
|
}
|
|
StatusCode SharedMemory::MakeSharedMemory(const int &size)
|
|
{
|
|
char touchPath[128] = {0};
|
|
if (access(mPath, F_OK) != 0) {
|
|
sprintf(touchPath, "%s %s", "touch", mPath);
|
|
fx_system_v2(touchPath);
|
|
}
|
|
key_t key = ftok(mPath, mProjectId);
|
|
if (key < 0) {
|
|
LogError("ftok failed.\n");
|
|
return CreateStatusCode(STATUS_CODE_NOT_OK);
|
|
}
|
|
mId = shmget(key, size, IPC_CREAT | 0666);
|
|
if (mId == SHMGET_FAILED) {
|
|
constexpr int MAYBE_CODE_22_MEANS_PEER_SIZE_WAS_NOT_MATCH = 22;
|
|
if (MAYBE_CODE_22_MEANS_PEER_SIZE_WAS_NOT_MATCH == errno) {
|
|
LogInfo("errno = %d, errmsg = %s\n", errno, strerror(errno));
|
|
return CreateSharedDataCode(SHARED_DATA_CODE_WRONG_PEER_PARAMETERS);
|
|
}
|
|
LogError("shmget failed. memory size = %d\n", size);
|
|
return CreateStatusCode(STATUS_CODE_NOT_OK);
|
|
}
|
|
LogInfo("Make shared memory succeed. memory size = %d\n", size);
|
|
return CreateStatusCode(STATUS_CODE_OK);
|
|
}
|
|
StatusCode SharedMemory::CleanSharedMemory(void)
|
|
{
|
|
if (SHMGET_FAILED == mId) {
|
|
LogError("mId error.\n");
|
|
return CreateStatusCode(STATUS_CODE_NOT_OK);
|
|
}
|
|
if (shmctl(mId, IPC_RMID, NULL) < 0) {
|
|
LogError("shmctl failed.\n");
|
|
return CreateStatusCode(STATUS_CODE_NOT_OK);
|
|
}
|
|
return CreateStatusCode(STATUS_CODE_OK);
|
|
}
|
|
void *SharedMemory::GetMemory(void)
|
|
{
|
|
if (SHMGET_FAILED == mId) {
|
|
LogError("mId error.\n");
|
|
return nullptr;
|
|
}
|
|
return shmat(mId, NULL, 0);
|
|
} |