Linux: system functions with output parameters

Source: Internet
Author: User
In Linux programming, you often need to call some system commands or shell scripts to help us complete some operations. In most cases, the system function is competent, but sometimes after the operation is completed, we need to get its output, and the system function is powerless. For this reason, I have compiled a function that allows the system to execute a command first and then use the pipeline technology to obtain its output. Code:
# Include <sys/types. h> # include <unistd. h> # include <stdlib. h> # include <stdio. h> # include <string. h> # define maxline 1024 // call the system command and obtain the output (equivalent to using system) // input: The system command to be called // output: system output after the command is called // maxlen: Maximum length of the output string int mysystem (char * input, char * output, int maxlen) {If (null = input | null = output) Return-1; int reslen; file * stream; memset (output, 0, maxlen); // create a pipeline, and write the content in the input to the pipeline stream = popen ( Input, "R"); // read data from the management and write the output array reslen = fread (output, sizeof (char), maxlen, stream); pclose (Stream ); return reslen;} int main (INT argc, char ** argv) {If (argc! = 2) {fprintf (stderr, "using :. /mysystem <cmd> \ n "); exit (1);} Char output [maxline]; mysystem (argv [1], output, maxline ); printf ("the result of '% s' is: \ n % s", argv [1], output); Return 0 ;}

Running example: qch @ Ubuntu :~ /Code $ GCC temp. C-o temp
Qch @ Ubuntu :~ /Code $./temp pwd
The result of 'pwd' is:
/Home/qch/code

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.