1

I'm using ubuntu 12.04 and i need to exchange an int variable from a cpp program to another. program A.cpp has to work with an int variable,but the value of this int variable has to be define in program B.cpp

In a very simple example:

B.cpp:

int x=0;
cout<<"define x\t";
cin>>x;

A.cpp:

int y=0;
y=x+5;
cout<<y;

A.cpp and B.cpp are two different cpp programs and variable x should not to be static,after i execute A.cpp i have to change x value without exit from the execution

How can i do this?

1 Answers1

3

The simplest way will be to create a named pipe. Under linux, you can use mkfifo() in A.cpp to create the pipe, then use it as an ordinary file. Open it for writing in A.cpp and write your y there, and open the same pipe in B.cpp for reading, and read x from there.

There are other approaches, but this seems to be the simplest.

See also How to send a simple string between two programs using pipes?

For a more detalied discussion, see https://en.wikipedia.org/wiki/Inter-process_communication . I think most worth mentioning for your case are

Socket — A data stream sent over a network interface, either to a different process on the same computer or to another computer on the network.

and

Shared memory — Multiple processes are given access to the same block of memory which creates a shared buffer for the processes to communicate with each other.

Community
  • 1
  • 1
Petr
  • 9,812
  • 1
  • 28
  • 52
  • cuold you do a the code example of above?? Sorry but i have never used pipes and i' m a new ubuntu user. – Marcello Chiurazzi May 24 '15 at 13:22
  • @MarcelloChiurazzi, please see another question that I refer to – Petr May 24 '15 at 13:25
  • I saw it and i understand how it works. i hope il will work for me. I will let you know. Anyway thanks ;) – Marcello Chiurazzi May 24 '15 at 13:31
  • the example aboout pipes is in c,how i can change it in c++? – Marcello Chiurazzi May 24 '15 at 13:40
  • @MarcelloChiurazzi, I think it will compile under C++ too. You can change the `open`/`close` work with files to streams, just as you usually work with files in a c++-program. You would also probably change `char*` to `string`, but as you have a number, not a string, this is not a problem. – Petr May 24 '15 at 13:42
  • I copy exactly the full example about reader and writer,if i compile both there are no problems but if i run writer or reader nothing happens! – Marcello Chiurazzi May 24 '15 at 13:53
  • You need to start both of them simultaneously, how else do you want them to pass data? – Petr May 24 '15 at 13:54
  • sure,i try `rosrun .... writer | reader ` but i have this error: `No command 'reader' found, did you mean: Command 'render' from package 'raster3d' (multiverse) reader: command not found´ – Marcello Chiurazzi May 24 '15 at 13:57