Execute shell commands using popen in c++ - visual-c++

I need to be able to execute some shell commands such as moving to the right directory where I have some files I need to decode and then decoding them using another command. I read some stuff about using popen but I didnt really understand how to use it for executing multiple commands.
Any pointers will be greatly appreciated :)
Thanks
FILE *pf;
char command[150];
char data[512];
// Execute a process listing
sprintf(command, "cd");
pf = _popen(command,"r");
sprintf(command, "cd Test_copy");
pf = _popen(command,"r"); */
sprintf(command, "java -jar Tool.jar -b x.fit x.csv");
pf = _popen(command,"r");
if(!pf){
fprintf(stderr, "Could not open pipe for output.\n");
return;
}
// Grab data from process execution
fgets(data, 512 , pf);
// Print grabbed data to the screen.
fprintf(stdout, "-%s-\n",data);
if (_pclose(pf) != 0)
fprintf(stderr," Error: Failed to close command stream \n");

Use ShellExecute to play with files (open with default application etc.). Use system to run shell commands.

No, don't. That would be like using a sledgehammer to knock on a door. Furthermore, it is "evil": http://www.cplusplus.com/forum/articles/11153/

Related

groovy "...".execute() works on windows but fails on linux

while this line works fine on windows on my linux box it returns exit code 1.
"gnuplot -e \"set output '${imageFile.toString()}'; filename='${dataFile.toString()}'; ${args}\" \"${plotFile.toString()}\"".execute()
But if I execute just this from the terminal everything works.
gnuplot -e "set output '/tmp/hrp-current.jpg'; filename='/tmp/a731265b-3736-4bb9-acf4-b92c1a09b999.csv'; " "/tmp/hrp/build/groovy/../gnuplot/hrp-current.gnuplot"
What am I missing here? It somehow has to do with the fact that gnuplot writes to a file because `some_command > some.file" also fails on linux with exit code 1 while it would work fine on windows.
.execute() on a String just splits on whitespace. You also don't need to quote the params for execution (you need to that for the shell). So execute an list of params instead:
["gnuplot", "-e", "set output '${imageFile.toString()}'; filename='${dataFile.toString()}'; ${args}", plotFile.toString()].execute()
Indeed it is some file writing issue so I need gnuplot to pipe its outout to stdout and then consume it from my groovy script where I read the outputstream and then save it to a file:
def out = new ByteArrayOutputStream()
def err = new ByteArrayOutputStream()
process.waitForProcessOutput(out, err)

STDOUT does not work programmatically via Groovy API

Using espeak command to generate an audio
espeak "Hello Mr. Toumi" --stdout > /tmp/audio123.wav
When i run this command using terminal , it works fine .
Prepare now in API for this command in Grails Service
#EspeakService.groovy
File speak(String message){
Process pr='espeak "'+message+'" --stdout > '+filePath(message);
pr.waitFor()
return new File(filePath(message));
}
When i run : espeakService.speak('Hello Mr. Toumi') , there is no file generated and also no error message displayed .
Any idea : Why does it not work programmatically ?
Java's external process execution mechanism is not a shell and doesn't support redirection using > like that. You should use a ProcessBuilder and do the redirection with that:
ProcessBuilder pb = new ProcessBuilder("espeak", message, "--stdout")
File out = new File(filePath(message))
pb.redirectOutput(out)
pb.redirectError(ProcessBuilder.Redirect.INHERIT)
pb.start().waitFor()
return out
redirections like > are done by shell. either use ['sh', '-c', 'espeak ...'].execute(). or just pick up the stdout from the process, which would save you from dealing with a file. e.g.
def p = "echo -n 666".execute()
p.waitFor()
assert p.in instanceof InputStream
assert p.in.text == "666"

How can Mono remove files matching a regex

As part of a project, the Mono program has to write a series of images to a movie. Therefore the images are first cached in the /tmp/ folder/ since their is a possibility that their are still images of a previous session. I want te remove these images. Therefore I use the following commands:
Process proc = new Process();
proc.EnableRaisingEvents = false;
proc.StartInfo.FileName = "rm";
proc.StartInfo.Arguments = "/tmp/output*";
proc.Start();
proc.WaitForExit();
However when the program is executed I get the following warning: /bin/rm: cannot remove '/tmp/output*': No such file or directory..
However when I executed /bin/rm /tmp/output* in the terminal (in user mode), the command doesn't seem to have a problem recognizing the files.
Why does this command doesn't work?
Spawning an external process for this is terrible. Just use the standard System.IO APIs, for instance:
foreach (var file in Directory.EnumerateFiles ("/tmp", "output*")) {
try {
File.Delete (file);
} catch {
; // optionally report error
}
}
You may also use the overload that takes a SearchOption argument to recursively search in subdirectories. See http://msdn.microsoft.com/en-us/library/dd383571.aspx.
Because you should run the shell to expand the glob pattern /tmp/output* into a an ordered array of file paths.
You could run sh -c "rm /tmp/output*" as a Mono process, but that is ugly
But you don't need a shell. You could for instance use mono readdir to build an array (or a list) of file paths to remove, then remove them by calling a function doing the unlink(2) syscall (I leave you to find how to do that in Mono).

Show output of a perl script in linux

I am using a web interface written in php that runs a perl script in a linux environment.It passes parameters(username,password,...) to the script . I want to view the output of the script without interfering with the process. Note that the script in his turn also passes data and excutes another program.
The script contains print commands like
if( $# ){
print "Error :".$#."\n";
print "skip...\n"; }
else{
}
I just want to view these results from the shell, also it would do it if i can save into a txt file .
thanks a lot!
Run the Perl program from the shell to see the output from print.
$ perl theprogram
⋮
Error : blah blah
skip...
⋮
Redirect STDOUT to save it into a file.
$ perl theprogram > theprogram.log
These are the very basics of shell usage, you already should know all this if you are a programmer. If not, read a Unix book for beginners.

linux - export output from apachetop to file

Is it possible to export output from apachetop to file? Something like this: "apachetop > file", but because apachetop is running "forever", so this command is also running forever. I just need to obtain actual output from this program and handle it in my GTK# application.
Every answer will be very appreciated.
Matej.
This might work:
{ apachetop > file 2>&1 & sleep 1; kill $! ; }
but no guarantees :)
Another way using linux is to find out the /dev/vcsN device that is being used when running the program and reading from that file directly. It contains a copy of the screen data for a given VT; I'm not sure if there is a applicable device for a pty.
Well indirectly apachetop is using the access.log file to get it's data.
Look at
/var/log/apache2/access.log
You'll simply have to parse the file to get the info you're looking for!/var/log/apache2/access.log

Resources