Executing Shell Commands from a C program |
If you want to run shell commands from within a C program there are several options:
pipe( )
,
fork( )
and
exec( )
but this is not that hard.
system( )
to run the command if input and output are not important.
popen( )
if control on either input or output is needed.
If you elect to bypass the shell, it can be handy to have
buffered I/O. STDIO functions are available on a file descriptor
with:
fdopen - associate a stream with a file descriptor
FILE *fdopen
(int fd, const char *mode);
scanf( )
and
printf( )
can be used on
fd
.
system - run shell command
int system
(const char *command);
system( )
is that I/O bypasses your
program unless you take steps to catch it.
popen - pipe to/from shell
FILE *popen
(const char *command, const char *type);
int pclose
(FILE *stream);
FILE *fp;
char *command;
/* command contains the command string (a character array) */
/* If you want to read output from command */
fp = popen
(command,"r");
/* read output from command */
fscanf(fp,....); /* or other STDIO input functions */
fclose(fp);
/* If you want to send input to command */
fp = popen
(command,"w");
/* write to command */
fprintf(fp,....); /* or other STDIO output functions */
fclose(fp);
The program cannot both send input to the command and read its output.
The file fp
behaves like an ordinary STDIO file.
Shell as a coprocess |
isatty( )
by dynamically linking in a version
that always returns true. This will require altering the environment
before calling the child coprocess, so that the child process's dynamic load
library path includes the revised isatty.
See isatty_preload.c
for how to do this in SUN Solaris.
expect
can be used to programatically
control a coprocess.
Last update: 2000 December 29