PHP - C Shared Memory

66 Views Asked by At

I am trying to write to a memory address from PHP and read from C. I can write successfully from PHP and read again from PHP end using this ;

$key = ftok("shmfile", 't');
$shm_id = shmop_open($key, "c", 0666, 100);
if (!$shm_id) {
    echo "Couldn't create shared memory segment.";
}
$data = "Hello, World!";
$bytes_written = shmop_write($shm_id, $data, 0);
if ($bytes_written != strlen($data)) {
    echo "Couldn't write the entire data to shared memory.";
} else {
    echo "Successfully wrote {$bytes_written} bytes to shared memory.\n";
}
$data_read = shmop_read($shm_id, 0, 100);
if (!$data_read) {
    echo "Couldn't read from shared memory segment.";
} else {
    echo "Data read from shared memory: " . $data_read . "\n";
}
shmop_close($shm_id);
echo "Shared memory segment closed.";

and my C code is as following;

int main()
{
    // ftok to generate unique key
    key_t key = ftok("shmfile", 65);

    // shmget returns an identifier in shmid
    int shmid = shmget(key, 1024, 0666 | IPC_CREAT);

    // shmat to attach to shared memory
    char* str = (char*)shmat(shmid, (void*)0, 0);

    cout << "Data read from memory:" << str;

    // detach from shared memory
    shmdt(str);

    // destroy the shared memory
    shmctl(shmid, IPC_RMID, NULL);

    return 0;
}

but when I run C code I get a segfault. I think I need to make some modifications in my C code to read what PHP has written.

Any ideas ?

1

There are 1 best solutions below

0
fun On

You use shm_open() for C and PHP.