Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sending data from c to perl

I need to send some data from c program to Perl program that both in running mode (Perl program in sleep mode and c program running, and c program sends data to Perl).

I know that, can write this program by socket and shared memory but I have performance problem. I think shared memory is better solution, and how can I signal to Perl program to wake up and resume run and read data that c send?

like image 709
hamSh Avatar asked Dec 07 '22 01:12

hamSh


2 Answers

You seem to have two questions here:

  1. how to share memory between the Perl program and your C program, and
  2. how to signal the Perl program there is new data available

Assuming you're on a system that allows SysV IPC calls, you can use IPC::ShareLite to share a chunk of memory between the two processes.

As usual with shared memory, you will have to ensure locks are in place. The module manual page for IPC::ShareLite seems to explain the intricacies and the method calls fairly well.

Regarding signaling the Perl program there is new data available, there's nothing stopping you from using... signals to achieve that! Your C program can send a SIGUSR1 to the Perl program, and the Perl program will access the shared memory and do stuff when receiving the signal, and sleep otherwise.

Have a look at perldoc perlipc for that, but the gist of it is something along these lines:

use strict;
use warnings;
use IPC::ShareLite;

# init shared memory

sub do_work {
    # use shared memory, as you just received a signal
    # indicating there's new data available
    my $signame = shift;
    # ...
}
$SIG{USR1} = \&do_work; # when signaled with SIGUSR1, call do_work()

# else just sleep
while(1) { sleep 1; }

Hope this helps,

-marco-

like image 136
mfontani Avatar answered Dec 26 '22 06:12

mfontani


  • Have a look on topic :"Embedding Perl (Using Perl from C)"-Chapter 21 Perl Programming Third Edition - Larry wall

  • See Internals and C language interface specially this part-Perl calling conventions from C.

    Then, you will come to know how to send data efficiently between C and Perl Program.

like image 29
Nikhil Jain Avatar answered Dec 26 '22 06:12

Nikhil Jain