新linux c程序中获取shell脚本输出(Get the shell script output in the new linux c program).docVIP

  • 38
  • 0
  • 约4.45千字
  • 约 9页
  • 2017-08-03 发布于河南
  • 举报

新linux c程序中获取shell脚本输出(Get the shell script output in the new linux c program).doc

新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 cant 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 UNIX advanced programming book gives a way through the anonymous pipe program output to the paging procedure example, so think of, we can also be external command results with applications connected by pipeline. Fork method is a sub process, and create an anonymous pipeline, execute the shell command in the sub proces

您可能关注的文档

文档评论(0)

1亿VIP精品文档

相关文档