Realization method of obtaining shell script output in Linux C program _c language

Source: Internet
Author: User
Tags call shell function prototype

1. Foreword
The Unix world has a famous saying: "A line of shell script than Wan C program", although this sentence is somewhat exaggerated, but it is undeniable that the use of scripting can greatly simplify some programming work. For example, to implement a ping program to test the connectivity of the network, the implementation of the PING function needs to write 200~300 line code, why not directly call the System ping command? Shell commands are typically invoked in a program through the system function. However, the system function only returns whether the command was executed successfully, and we may need to get the result of the shell command outputting on the console. For example, after performing an external command ping, if execution fails, we want to get the ping return information.

2. Use of temporary documents
The first thought was to redirect the command output to a temporary file, read the temp file in our application, get the results of the external command execution, as shown in the following code:

Copy Code code as follows:

#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);
}

This use of temporary files as a bridge between application and external commands, the need to read files in the application, and then delete the temporary file, more cumbersome, the advantage is simple, easy to understand. Is there a way of not using temporary documents?

3. Using anonymous Pipes
In the <<unix Environment Advanced Programming >> book gives an example of an anonymous pipeline that outputs program results to a paging program, so it is thought that we can also connect the results of an external command to the application through a pipeline. The method is to fork a subprocess, create an anonymous pipe, execute the shell command in the subprocess, and DUP its standard output to the input of the anonymous pipe, and the parent process reads from the pipe to obtain the output of the shell command, as follows:

Copy Code code as follows:

/** * Enhanced system function that returns the output of the system call *
* @param [in] cmdstring a command string that invokes an external program or script
* @param [out] buf a buffer that returns the result of an external command
* @param length of the [in] Len buffer buf
* * @return 0: Success; -1: Failure */
int Mysystem (char* cmdstring, char* buf, int len)
{
int fd[2]; pid_t pid;
int n, Count;
memset (buf, 0, Len);
if (pipe (FD) < 0)
return-1;
if ((PID = fork ()) < 0)
return-1;
else if (PID > 0)/* Parent Process * *
{
Close (fd[1]); /* Close Write End * *
Count = 0;
while ((n = read (fd[0], buf + count, len) > 0 && count > Len)
Count = N;
Close (fd[0]);
if (Waitpid (PID, NULL, 0) > 0)
return-1;
}
else/* Child process * *
{
Close (fd[0]); /* Close Read End * *
if (fd[1]!= Stdout_fileno)
{
if (Dup2 (fd[1], Stdout_fileno)!= Stdout_fileno)
{
return-1;
}
Close (fd[1]);
}
if (Execl ("/bin/sh", "sh", "-C", Cmdstring, (char*) 0) = = 1)
return-1;
}
return 0;
}

4. Use of Popen
In the course of learning Unix programming, the discovery system also provides a popen function that can be very simple to handle the call shell, and its function prototype is as follows:
FILE *popen (const char *command, const char *type);
The function is to create a pipe, fork a process, and then execute the shell, and the shell's output can be obtained by reading the file. This method avoids the creation of temporary files and is not limited by the number of output characters, and is recommended for use.
Popen uses FIFO pipes to execute external programs.
Copy Code code as follows:

#include <stdio.h>
FILE *popen (const char *command, const char *type);
int Pclose (FILE *stream);

Popen determines the input/output direction of the command by Type R or W, and R and W are relative to the command's pipe. R indicates that the command is read from the pipe, and W represents the file stream pointer that the command outputs to its stdout,popen through the pipeline to its FIFO pipe. Pclose is used to close this pointer when the end is used.
Let's look at an example:
Copy Code code as follows:

#include <sys/types.h>
#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
int main (void)
{
FILE *stream;
FILE *wstream;
Char buf[1024];
memset (buf, '/0 ', sizeof (BUF));//initialize BUF to avoid writing back like garbled to file
stream = Popen ("Ls-l", "R"); To read the output of the "ls-l" command through a pipe ("r" parameter) to the file* stream
Wstream = fopen ("Test_popen.txt", "w+"); Create a new writable file
Fread (buf, sizeof (char), sizeof (BUF), stream); Reads the data stream just file* stream into the BUF
Fwrite (buf, 1, sizeof (BUF), Wstream)//write the data in the BUF to the corresponding stream in the file *wstream, and also to the files
Pclose (stream);
Fclose (Wstream);
return 0;
}
[Root@localhost src]# gcc popen.c
[Root@localhost src]#./a.out
[Root@localhost src]# Cat Test_popen.txt

Total 128
-rwxr-xr-x 1 root Root 5558 09-30 11:51 a.out
-rwxr-xr-x 1 root root 542 09-30 00:00 child_fork.c
-rwxr-xr-x 1 root 09-30 00:13 execve.c
-rwxr-xr-x 1 root root 1811 09-29 21:33 fork.c
-rwxr-xr-x 1 root root 162 09-29 18:54 GETPID.C
-rwxr-xr-x 1 root root 1105 09-30 11:49 popen.c
-rwxr-xr-x 1 root root 443 09-30 00:55 system.c
-rwxr-xr-x 1 root 0 09-30 11:51 test_popen.txt
-rwxr-xr-x 1 root root 4094 09-30 11:39 test.txt


5. Summary
Statistical data show that the defect rate of code is certain, regardless of the language used. Linux provides a lot of utilities and scripts to invoke tools and scripts in a program that can simplify programs and reduce the number of code flaws. Linux shell script is also a powerful tool, we can script as needed, and then call custom script in the program.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.