Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations wOOdy-Soft on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Unix shell command inside a C/C++ program?

Status
Not open for further replies.

csd

Programmer
May 10, 2001
6
US
Friends:
Please tell me if it's possible to run an Unix shell command
inside a C/C++ program? The question may be too stupid but we do need run such a command at some
point inside the code, then continue to execute the rest part of the code...

If possible, how to do that?

Thanks.

csd
 
In both C and C++ you can use the system() command:

#include <stdlib.h> /* <cstdlib> for C++ */

char command[]=&quot;find . -name '*.c' -o -name '*.cc' | xargs egrep -n 'system\((\&quot;.+\&quot;|NULL)\)'&quot;;

system(command);

system() won't give you the command's output though. If you need to see the command's output in your program, you can use system() and dump it to a file and then parse the file:

char command[]=&quot;find . -name '*.c' -o -name '*.cc' | xargs egrep -n 'system\((\&quot;.+\&quot;|NULL)\)' > out.txt 2>&1&quot;;
FILE *fp;

system(command);

fp=fopen(&quot;out.txt&quot;,&quot;r&quot;);
if (fp) {
/* read the file line by line or whatever */

A better way is to use popen() if your implementation provides it. It treats the command's output as though it were an ordinary stream:

#include <stdio.h>

int main(void)
{
char command[]=&quot;find . -name '*.c' -o -name '*.cc' | xargs egrep -n 'system\((\&quot;.+\&quot;|NULL)\)'&quot;;

FILE *proc=popen(&quot;ls&quot;,&quot;r&quot;);
char line[100];

if (fp) {
while (fgets(line,sizeof line,proc)) {
/* line contains each line of the process's
* output
*/
}
}
pclose(fp); /* pclose(), not fclose() */
return 0;
}





Russ
bobbitts@hotmail.com
 
If you use a pipe you can put and read information from the command.
Here is a sample to work with a pipe. This sample looks if a program is already running and returns the number of running programs.
But you can write as well to a pipe like to a file.

int send_emsgs_already_running ()
{
FILE *fps;
const char *ps = &quot;ps -e|grep iaksend_emsgs&quot;;
char pspid[10], pstty[15], pstime[10], pscmd[300];
int rc = 0;
int frc = 0;

fps = popen (ps, &quot;r&quot;);
if (fps == NULL)
{
Errorhandling...
return -1;
}
while (frc != EOF)
{
strcpy ((char *)pscmd, &quot;&quot;);
frc = fscanf (fps, &quot;%s %s %s %s&quot;, pspid, pstty, pstime, pscmd);
if (strlen (pscmd))
{
// printf (&quot;Found programs: %s %s %s \n&quot;, pspid, pstty, pstime, pscmd);
if (! strcmp ((char *)pscmd, &quot;iaksend_emsgs&quot;))
{
rc += 1;
}
}
}
pclose (fps);
return rc;
}



A link where you can find more information about pipes:
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top