Launching A Command Shell

This week, I will discuss two functions that launch a command shell.

The first function is system(), which is declared in "stdlib.h" as


int system(const char * cmd);

system() launches a shell as a child process, passes a command for the

shell to execute, and returns the child's status. Note that the status

returned is the exit code of the command shell, not the status of a

process that was subsequently launched from the command shell. The

following call returns 0 if the command shell was successfully

launched; it doesn't return the exit status of the program "calculator":

int stat=system("calculator");

The child process writes to stdout and receives input from stdin. The

parent process waits until the shell exits. Thus, system() is mostly

useful for implementing menu-based applications. Often, a parent

process needs to read from the child process or send data to it. For

this purpose, you should use the popen() function.

popen() is similar to system() except that it returns FILE * and takes

an additional parameter, the mode type:

FILE * popen(const char *cmd, const char *mode);

The two mode types are "r" -- if the parent wishes to read from the

child's standard output -- and "w" -- if the parent wishes to write to

the child's standard input (you can't do both read and write with popen

()). A successful popen() call returns a non-null FILE pointer. When

you write to that file, you're actually writing to the child's stdin,

and when you read from that file you're reading the child's stdout. You

must call pclose() before exiting from the parent process to close the

stream and terminate the child process, if it's still running. It's

also recommended that you flush the stream after every write operation

to avoid buffering delays. The following program creates an expression

string that is passed to another program, calc, which in turn performs

all the actual calculation. Notice how the string is passed to the

child's stdin using fprintf():

#include stdio.h

int main()


char buff[1024];

int stat;

FILE* pipe;




perror("calc failed");

exit -1


printf("enter a math expression: ");

fgets(buff, sizeof(buff), stdin); /*read expression*/

/*send user's expression to calc program using pipe*/

fprintf(pipe,"%s", buff);

fflush(pipe);/*avoid stdio buffering delay*/

stat=pclose(pipe); /*close child's pipe*/

return stat;


What’s wrong? The new clean desk test
Join the discussion
Be the first to comment on this article. Our Commenting Policies