C language returns Shell results, C language returns shell

Source: Internet
Author: User
Tags call shell

C language returns Shell results, C language returns shell

In Linux programming, if we need to call shell commands or scripts, we usually use the system method. For example, system ("ls ")

The return value of this method is 0 or-1, that is, success or failure. In some cases, what should we do if we want to obtain the results of shell command execution?

We can redirect the shell command results to the file and then read the file, such:

System ("ls> result.txt ")

FILE * fp = fopen (result, "r ")

You can also directly use pipelines, as shown in the following example:

#include <stdio.h>#include <stdlib.h>#include <unistd.h>#include <sys/types.h>#include <strings.h>#include <string.h>char* shellcmd(char* cmd, char* buff, int size){    char temp[256];    FILE* fp = NULL;    int offset = 0;    int len;        fp = popen(cmd, "r");    if(fp == NULL)    {        return NULL;    }    while(fgets(temp, sizeof(temp), fp) != NULL)    {        len = strlen(temp);        if(offset + len < size)        {            strcpy(buff+offset, temp);            offset += len;        }        else        {            buff[offset] = 0;            break;        }    }        if(fp != NULL)    {        pclose(fp);    }    return buff;}int main(void){    char buff[1024];    memset(buff, 0, sizeof(buff));    printf("%s", shellcmd("ls", buff, sizeof(buff)));    return 0;}

  

Note: The C language calls the shell command to create a new process for execution, the execution speed is very slow, it is best not to use C, Shell Mixed Programming.

 

Related Article

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.