新linux c程序中获取shell脚本输出(Get the shell script output in the new linux c program)
1. Preface
There is a famous saying in the Unix community: "one line of shell scripts is better than a thousand lines of C programs". Although this sentence is somewhat exaggerated, it can not be denied that it can greatly simplify some programming work with the aid of the script. For example, to implement a ping program to test the connectivity of the network, and to implement the ping function, you need to write the 200~300 line code. Why can't you call the ping command of the system directly? Usually in a program, the shell command is invoked through the system function. However, the system function only returns the command if it succeeds, and we may need to get the output of the shell command on the console. For example, after execution of the external command Ping, if the execution fails, we want to get the return information of ping.
2. use temporary files
The first thought is to redirect the command output to a temporary file, read the temporary file in our application, and get the external command execution results, as shown in the following code:
#define CMD_STR_LEN 1024
Int mysystem (char*, cmdstring, char*, tmpfile)
{
Char cmd_string[CMD_STR_LEN];
Tmpnam (tmpfile);
Sprintf (cmd_string,%s >%s, cmdstring, tmpfile);
Return system (cmd_string);
}
The use of temporary files as between the application and the external command link, you need to read a file in your application, then delete the temporary files, more complicated, it is easy to implement, easy to understand. Is there any way without resorting to temporary documents?
3. using anonymous pipes
In the environment of <