Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sharing memory between Java and PHP?

Can someone provide me links or snippets where a PHP process writes to memory and a Java process reads from the shared memory?

Thanks for the wonderful answers.

Edited question : Suppose i create a shared memory in php like this

<?php
$shm_key = ftok(__FILE__, 't');
$shm_id = shmop_open($shm_key, "c", 0644, 100);
$shm_bytes_written = shmop_write($shm_id, $my_string, 0);
?>

Now is there some method by which i can pass the value of $shm_id and then read from it in java.

like image 396
ayush Avatar asked Dec 10 '22 10:12

ayush


2 Answers

If you don't need synchronized interaction between Java and PHP - I would use memcached, membase or some other type of memory key store.

Another way, for huge amount of data stream, is using Unix named pipe (FIFO). It is common way in IPC (Inter Process Communication). First create the pipe as normal file using mkfifo command. Add some reasonable access rights. In PHP open the pipe with r+ mode as normal file and write, finally close. On Java side you keep it open as normal file and read continuously by FileInputStream with blocking read/readline or nonblocking NIO.

In comparison to SHM, you don't have to play with JNI, shared memory synchronization, ring buffer implementations, locking and memory leaks. You get simple read/write and FIFO queue at lowest development cost.

You delete it as normal file. Don't use random access or seek as it is real stream without history.

like image 107
gertas Avatar answered Dec 28 '22 02:12

gertas


Why don't you use some message queues? You cannot literally write into memory of a JVM or share it with other processes.

In order to communicate between others you can make use of a Message Queue technology. You can have message queue running and PHP could easily transfer the data. The java application could read the queue, get the data and process accordingly.

like image 25
Abdel Raoof Olakara Avatar answered Dec 28 '22 02:12

Abdel Raoof Olakara