How to plot graphs in Gnuplot in Real time in C++? [closed] - c++

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
I'm trying to plot a graph in real time using GNUplot and C++.
Does anyone know of any good libraries that does this?
Thanks

gnuplot supports input via pipes (on windows, there's a separate executable for this, pgnuplot). Then your program can send new commands to gnuplot, such as replot, just as if you were typing them into the gnuplot interface directly.
How you set up the pipe connection and write to the sending end of the pipe from your C++ program varies by operating system, so you'll have to tell us what you're using if you want more help.
On Windows, there's CreatePipe and then you set the hStdInput element of the STARTUPINFO struct you pass to CreateProcess. Ditto with hStdOutput if you need the status messages from pgnuplot.
On POSIX (Unix, Linux, Mac OSX, etc), you can just use popen as the quick way to get a unidirectional connection. For bidirectional, it works more like on Windows: pipe to get handles to the ends, then fork and in the child process call dup2 to associate stdin and stdout with the pipe, then exec to have gnuplot replace the child process, keeping the pipes you set up.
EDIT: From the gnuplot documentation:
The special filename ’-’ specifies
that the data are inline; i.e., they
follow the command. Only the data
follow the command; plot options like
filters, titles, and line styles
remain on the plot command line. This
is similar to << in unix shell script,
and $DECK in VMS DCL. The data are
entered as though they are being read
from a file, one data point per
record. The letter "e" at the start of
the first column terminates data
entry. The using option can be applied
to these data — using it to filter
them through a function might make
sense, but selecting columns probably
doesn’t!

Have you tried gnuplot interfaces in ANSI C?, this is an interface for C but in the same links there are some interface for C++. Or you could try PlPlot.

If you're interested in soft-realtime plotting, you're probably best of using a hardware accelerated graphics api (such as OpenGL), and plotting the chart yourself.

Look at http://search.cpan.org/~dkogan/feedGnuplot-1.08/bin/feedGnuplot This is a commandline utility, but also works well if controlled from a program.

In my C++ code, this worked (on mac OsX mavericks, using g++ Apple LLVM version 5.0):
#include <sys/types.h>
#include <unistd.h>
...
// ready to make a plot
pid_t childpid=fork();
if(childpid==0) {
// child process makes plot
std::FILE* pipehandle=popen("gnuplot -persist","w");
// make some plot. You can send multiple commands to the pipe each ending in \n
std::fprintf(pipehandle,"plot \"results.txt\" using 1:2 with lines\n");
std::fprintf(pipehandle,"quit\n");
std::fflush(pipehandle);
std::fclose(pipehandle);
// child process exits
exit(0);
}
// parent process waits for child process to exit
waitpid(childpid,NULL,0);
// you can now repeat to make other gnuplots; all will appear simultaneously in the
// terminal and are persistent after the parent process has finished.

Related

How to run a bash commands in C++ without using system in linux [duplicate]

This question already has answers here:
How can I execute an external commands in C/Linux without using system, popen, fork, exec?
(1 answer)
Writing my own shell... stuck on pipes?
(9 answers)
Closed 1 year ago.
I want to take an input, a bash command, and be able to execute that input from my CPP program. This is for school and we are not allowed to use "system" so I do not know any other way to do this. Also, the program can take up to 3 commands via pipe. I've looked up how to do this but it just gets more confusing. If there are any resources or a question similar to this that has been answered please link. Thanks.
Here is a similar question.
Basically, for the shell part, you are going to use fork and some form of exec (e.g., execve) to get that to execute.
For pipes, you're going to have to use the pipe command in C++, which will allow you to write and read from the pipe from separate children (in your case, up to two pipes, so you can create a 2x2 array of file descriptors, as a normal pipe is just a 2 element array). You should write the output of one program into the correct pipe and read it from the pipe in the next child once the first terminates.

Access data from terminal

I have to write a program that intercepts data from terminal and i have to parse it. After processing when the data, i have to parse it before it goes to stdout.
I can't use tee or commands like prog > file 2>&1 as the program is going to be interactive.
For example :
If the user types ls in the terminal i have to parse it then it should go operating system and then when I get the result after processing I ll have to again parse it before it's displayed in the terminal.
I did my research and I think I can achieve it through pseudo terminal interfaces ( pty ).
Please let me know if there is a better way to achieve it.
I am using cpp and bash and the platform is *nix.
Update:
I can also use libexpect from expect.
I am not sure what do you mean here - you mean interactive program as "working in another terminal communicating with user" or even displaying GUI?
How does it specify the terminal? It is probably important what is program layout here (which program starts which).
If your application uses GUI to communicate with user, then I would simply do it this way:
start bash with sdtin and stdout attached to pipes,
your program reads & writes to it's end's of those pipes, parses data, and reads/writes on it's own stdin&stdout - so it appears on it's terminal.
If you mean controlling different terminal than your application's, it gets though since system generally does not expect program operating on multiple terminals. I don't think it's possible to filter communication between terminal and already working application attached to it. Starting another process spawning another terminal might be an option - to have basically two terminals working in sync. But then you will have to synchronize both processes by some other means (named pipes, network connection or some other IPC).
If you provide more detail on your program I might provide more directed help.
PS Don't tell me that you are writing some terminal keylogger ')
EDIT:
Your program is probably GUI based then - what i would recommend would be something similar to answer linked by banuj.
Best option will probably be to create three pipes, then fork, and in child process assign corresponding ends of pipes to stdin, stdout and stderr. Then child process should exec into shell - probably bash, although I am not sure if other shells would sound better if read out loud ;) Main process will be able to read/write other ends of mentioned pipes, parsing both inputs and outputs to bash and programs it runs.
You could also exec directly to commands user specifies, but that forces you to take over tedious job of a shell - managing current directory, environment variables, job control and so on.
Using above method might however cause some trouble - some programs (usually in security related contexts - eg. su(do) asking for password) will try to bypass stdin/stdout anyway and read directly from terminal device. I am not sure what can you do in such case - programing your own terminal emulator would be an option, but I don't know if you want to go this deep into system programming for this.
If you want some code snippet's, if you don't know how to do above, just ask ;)

Wrapping executable's input and output in c++

There is a program in java (Minecraft) and for the server part of it, it opens up in a terminal and prompts the user for commands, as well as give feedback for loading progress and other stuff. How can I make a c++ "wrapper" to automatically send commands to the terminal, and receive the response?
I could automate commands such as say and kick with GUI elements. I am running a mac with OSX Lion.
It presumably reads and writes stdin/stdout. You should look up executing a binary (in this case java.exe) in c++ and how to read and write to it. Alternatively, you could write a wrapper in Java that gives you control without having to parse the text output.
The answer to this question would depend on the operating system as different systems use different approach how to deal with the standard input and output channels. On a UNIX system you'd create a pipe(2) (or two if you want to capture standard output and standard error separately), fork(2) the "server", use close(2) and dup(2) to put the various file descriptors into place, and then execve(2) the actual program. After this you can read/write to various descriptors.

Communication with a script from a C++ program

I have a c++ program (very complicated, and lengthy both in code and execution time).
Once in a while this program stops and calls a user-specified shell script.
Before calling the script, my program creates a .out file with current data. I call the script via system() command. The script then reads the .out file, and creates its own script.out file and exits.
Then the system() function call ends, and my program reads and parses the script.out file.
Question: is there a better way to execute communication between my c++ program and a random shell script?
My intent is to have full communication between the two. Script could virtually "ask" the program "What data do you have right now?" and the program would reply with some strict convention. Then the script could say "Add this data...", or "delete all your previous data" etc.etc.
The reason I need this is because the shell script tells the program to modify its data. The exact data that was put in the original .out file. So after the modification is done -- the actual data held by the program does not correspond to the data written in the .out file.
Thanks!
P.S.
I swear I've searched around, but everyone suggests an intermediate file.
There are certainly ways to do that without intermediate files. The most common approach is to use command line arguments for input, and pipes for standard output; others also use pipes for input. The most straight-forward alternative to system then is to use popen.
On a unix-like system? Perhaps pipe (2) will work for you?
From the man page (Mac OS X 10.5 version):
SYNOPSIS
#include <unistd.h>
int pipe(int fildes[2]);
DESCRIPTION
The pipe() function creates a pipe (an object that allows unidirectional
data flow) and allocates a pair of file descriptors. The first descrip-
tor connects to the read end of the pipe; the second connects to the
write end.
You will, of course, have to follow the creation of the pipes with a fork and exec pair. Probably this has already been answered in detail, and now you know what to search on...
It's been a while since I did this, but:
In the main process, before forking the sub-process you call pipe twice. Now you have two pipes and control both ends of both of them.
You fork.
The main process will read from one pipe and write from the other. It doesn't matter which is which, but you need to be clear about this.
The child process will call one of the exec family of function to replace it's image with that of the shell you want to run but first you will use dup2 to replace it's standard input and output with the ends of the two pipes (again, this is where you need to be clear about which pipe is which).
At his point you have two processes, the main process can send things into one pipe ad they will be received on the standard input of the script, and anything the script writes to it's standard output will be sent up the other pipe to the controlling process. So they take turns, just like interacting with the shell.
You can use pipes or (maybe more convenient) sockets - for example frontends to gdb, or expect do that. It would require changes to your shell scripts, and switching from system() to more low-level fork() and exec().
It's rather complicated so please, be more specific about your environment and what you need to clarify.
You are asking the question on Interprocess Communication (IPC).
There are a lot of ways to do that. You can do a simply search and Internet will return you most answers.
If I am not wrong, Google chrome uses a technique called Named Pipe.
Anyway, I think the most "portable way" is probably a file. But if you know you are working on which operating system, you can definitely use most of the IPC techniques.

Crossplatform Bidirectional IPC

I have a project that I thought was going to be relatively easy, but is turning out to be more of a pain that I had hoped. First, most of the code I'm interacting with is legacy code that I don't have control over, so I can't do big paradigm changes.
Here's a simplified explanation of what I need to do: Say I have a large number of simple programs that read from stdin and write to stdout. (These I can't touch). Basically, input to stdin is a command like "Set temperature to 100" or something like that. And the output is an event "Temperature has been set to 100" or "Temperature has fallen below setpoint".
What I'd like to do is write an application that can start a bunch of these simple programs, watch for events and then send commands to them as necessary. My initial plan was to something like popen, but I need a bidrectional popen to get both read and write pipes. I hacked something together that I call popen2 where I pass it the command to run and two FILE* that get filled with the read and write stream. Then all I need to do is write a simple loop that reads from each of the stdouts from each of the processes, does the logic that it needs and then writes commands back to the proper process.
Here's some pseudocode
FILE *p1read, *p1write;
FILE *p2read, *p2write;
FILE *p3read, *p3write;
//start each command, attach to stdin and stdout
popen2("process1",&p1read,&p1write);
popen2("process2",&p2read,&p2write);
popen2("process3",&p3read,&p3write);
while (1)
{
//read status from each process
char status1[1024];
char status2[1024];
char status3[1024];
fread(status1,1024,p1read);
fread(status2,1024,p2read);
fread(status3,1024,p3read);
char command1[1024];
char command2[1024];
char command3[1024];
//do some logic here
//write command back to each process
fwrite(command1,p1write);
fwrite(command2,p2write);
fwrite(command3,p3write);
}
The real program is more complicated where it peeks in the stream to see if anything is waiting, if not, it will skip that process, likewise if it doesn't need to send a command to a certain process it doesn't. But this code gives the basic idea.
Now this works great on my UNIX box and even pretty good on a Windows XP box with cygwin. However, now I need to get it to work on Win32 natively.
The hard part is that my popen2 uses fork() and execl() to start the process and assign the streams to stdin and stdout of the child processes. Is there a clean way I can do this in windows? Basically, I'd like to create a popen2 that works in windows the same way as my unix version. This way the only windows specific code would be in that function and I could get away with everything else working the same way.
Any Ideas?
Thanks!
On Windows, you invoke CreatePipe first (similar to pipe(2)), then CreateProcess. The trick here is that CreateProcess has a parameter where you can pass stdin, stdout, stderr of the newly-created process.
Notice that when you use stdio, you need to do fdopen to create the file object afterwards, which expects file numbers. In the Microsoft CRT, file numbers are different from OS file handles. So to return the other end of CreatePipe to the caller, you first need _open_osfhandle to get a CRT file number, and then fdopen on that.
If you want to see working code, check out _PyPopen in
http://svn.python.org/view/python/trunk/Modules/posixmodule.c?view=markup
I think you've made a very good start to your problem by using the popen2() function to abstract away the cross-platform issues. I was expecting to come and suggest 'sockets', but I'm sure that's not relevant after reading the question. You could use sockets instead of pipes - it would be hidden in the popen2() function.
I am 99% sure you can implement the required functionality on Windows, using Windows APIs. What I cannot do is point you to the right functions reliably. However, you should be aware the Microsoft has most of the POSIX-like API calls available, but the name is prefixed with '_'. There are also native API calls that achieve the effects of fork and exec.
Your comments suggest that you are aware of issues with availability of data and possible deadlocks - be cautious.