ravi - 2022-06-21

Hello, Greetings!,

We are trying to utilize CODESYS Shared Memory on Raspberry Pi 4, we are unable to move forward due to Segmentation fault in Pi OS (c program compiled using gcc). On running, a valid memory address is shown in CODESYS but unable to read it on Pi using the c program. Appreciate your help.

CODESYS IDE Version 3.5.18.20
Raspberry Pi 4
CODESYS Runtime 4.4.0.0 is installed on Pi

Step 1 :

Create a structure structWrite of type DataExchange
Write a static value 300 to structWrite.Val1
Create a named shared memory "ShMem"
Write the value structWrite.Val1 to shared memory

Step 2 :

Create a structure DataExchange
Create a prointer *pRead to DataExchange
Open the shared memory "ShMem" using shm_open()
Tried using O_CREAT | O_RDWR, S_IRWXU | S_IRWXG flags.. did not work
Map to the shared memory using mmap()
Read value and print
Unmap using munmap()
Unlink using shm_unlink()

Error** :

shm_open() is failed and returns -1
Not able to read shared memory
Generates Segmentation fault

Here is the code for reference:

Codesys Program:

Declarations:

TYPE DataExchange :
STRUCT
Val1 : DINT;
END_STRUCT
END_TYPE

PROGRAM PLC_PRG
VAR
hShMemWrite: RTS_IEC_HANDLE;
ResultWrite: RTS_IEC_RESULT;
WriteResult: RTS_IEC_RESULT;
structWrite: DataExchange;
ulSize: UDINT := SIZEOF(structWrite);
create: BOOL ;
iWrite: __UXINT;
END_VAR

Code:

IF not create THEN
structWrite.Val1:=300;

hShMemWrite := SysSharedMemoryCreate('ShMem', 0, ADR(ulSize), ADR(ResultWrite));
iWrite := SysSharedMemoryWrite(hShMemWrite, 0, ADR(structWrite), SIZEOF(structWrite), ADR(WriteResult));

create:=TRUE;

END_IF;

C Program

(compiled using gcc)

include <stdio.h>
include <stdlib.h>
include <sys mman.h="">
include <sys stat.h="">
include <fcntl.h>
include <unistd.h>
include <string.h></string.h></unistd.h></fcntl.h></sys></sys></stdlib.h></stdio.h>

struct DataExchange
{
int i1;
};

int main(int argc, char *argv)
{
struct DataExchange
pRead;
char sSharedMemReadName[100] = "ShMem";

/*int fdRead = shm_open(sSharedMemReadName, O_CREAT | O_RDWR, S_IRWXU | S_IRWXG);*/

int fdRead = shm_open("ShMem", O_RDONLY, S_IRUSR);

printf("Shared Memory Read: %s %d\n\n",sSharedMemReadName, fdRead);
ftruncate(fdRead, sizeof(*pRead));
pRead = mmap(0, sizeof(*pRead), PROT_READ | PROT_WRITE, MAP_SHARED, fdRead, 0);

printf("pRead->i1: %d : %d\n", pRead->i1);

close(fdRead);
munmap(pRead, sizeof(*pRead));
shm_unlink(sSharedMemReadName);

exit(0);

}