|Executing Shell Commands from a C program|
If you want to run shell commands from within a C program there are several options:
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
fdopen - associate a stream with a file descriptor
fdopen(int fd, const char *mode);
printf( )can be used on
system - run shell command
system(const char *command);
system( )is that I/O bypasses your program unless you take steps to catch it.
popen - pipe to/from shell
popen(const char *command, const char *type);
The program cannot both send input to the command and read its output. The file
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);
fpbehaves 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.
expectcan be used to programatically control a coprocess.
Last update: 2000 December 29