Executing Shell Commands with system() and popen() in C
If you want to run shell commands from within a C program there are several options:
- Do not use the shell, but bypass the shell and run the commands directly within your program. Many of the basic utilities can be accessed easily enough and system calls are available for system programming tasks. You may need to
pipe( ),fork( )andexec( )but this is not that hard. - Use
system()to run the command if input and output are not important. - Use
popen()if control on either input or output is needed. - In C++, you might use member function STREAM.
rdbuf(), which is only available for C++ streams. - Run the shell as a coprocess. This is fraught with many difficulties, so it won't be discussed here.
Pipe to/from Shell with popen() (and pclose())
Prototypes:
FILE *popen(const char *command, const char *type); int pclose(FILE *stream);
Note that a pointer (FILE *) is initialized for just one call, and that after the call the file
should be closed. In between you can read from the thus created file with fscanf() and other file-reading functions, alternatively write to it with fprintf() and other file-writing functions.
Typical usage is:
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 (handle) fp behaves like an ordinary STDIO file.
Buffered I/O with fdopen()
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, which associates a stream to a file descriptor.
FILE *fdopen(int fd, const char *mode);
After this call, STDIO buffered I/O and standard I/O functions such as scanf() and printf() can be used on fd.