Operating System - Linux
1827497 Members
2531 Online
109965 Solutions
New Discussion

running shell scrit form C++

 
msbinu
Advisor

running shell scrit form C++

Hi ,

I have to run a shell scipt form my C++ file and get the output obtained by running the script in my cpp file.
Can any one throw some light as to how to do this

Thanks in advance
regards
Binu
6 REPLIES 6
Arunvijai_4
Honored Contributor

Re: running shell scrit form C++

Hi Binu,

Have you tried using "system()" call ? I think, it should be helpful to you

-Arun
"A ship in the harbor is safe, but that is not what ships are built for"
A. Clay Stephenson
Acclaimed Contributor

Re: running shell scrit form C++

The system() function is not a wise choice as the only thing returned is the exit status of the command. You really want to open a pipe for reading via popen() to capture the output of a shell script. pclose() will return the exit status of the command. Man popen, pclose for details.
If it ain't broke, I can fix that.
Bill Hassell
Honored Contributor

Re: running shell scrit form C++

And make sure that *all* of your scripts have the interpreter listed in line 1. Scripts will run without this line but only under specific circumstances. The line looks like this:

#!/usr/bin/sh

(or ksh or csh or perl....whatever)
Without that line, there is no way to know how to run the script (scripts always require an interpreter, typically a shell or scripting language amd the C program is not a shell)


Bill Hassell, sysadmin
Sung Oh
Respected Contributor

Re: running shell scrit form C++

hi Binu,

You can use "sprintf" function

eg.
(void)sprintf(cmd, "cat /proc/iomem 2>/dev/null", idedb[i].device);

and you can use "popen" function

if ((fp = (FILE *)popen("cat /proc/iomem 2>/dev/null", "r")) == NULL) {
error ("popen failed when trying to view iomem data");
return (1);
}

http://www.phim.unibe.ch/comp_doc/c_manual/C/FUNCTIONS/popen.html

Regards,
Sung
A. Clay Stephenson
Acclaimed Contributor

Re: running shell scrit form C++

WRONG:
(void)sprintf(cmd, "cat /proc/iomem 2>/dev/null", idedb[i].device);

The sprintf command by itself will do nothing except build the string "cmd" that might later be used in a system(cmd) function or a popen(cmd,"r").
If it ain't broke, I can fix that.
msbinu
Advisor

Re: running shell scrit form C++

Thanks all for your help