zoukankan      html  css  js  c++  java
  • shell c 混合编程 system 输出数据到变量

    shell c 混合编程 system 输出数据到变量

    方法一: (popen)

    #include <stdio.h>
    #include <stdlib.h>


    int main( int argc, char *argv[] )
    {

    FILE *fp;
    int status;
    char path[1035];

    /* Open the command for reading. */
    fp = popen("/bin/ls /etc/", "r");
    if (fp == NULL) {
    printf("Failed to run command\n" );
    exit;
    }

    /* Read the output a line at a time - output it. */
    while (fgets(path, sizeof(path)-1, fp) != NULL) {
    printf("%s", path);
    }

    /* close */
    pclose(fp);

    return 0;
    }



    方法二:

    #include <stdio.h>
    #include <stdlib.h>



    static int my_system(const char* pCmd, char* pResult, int size)
    {
    int fd[2];
    int pid;
    int count;
    int left;
    char* p = 0;
    int maxlen = size - 1;
    memset(pResult, 0, size);
    if(pipe(fd))
    {
    printf("pipe error\n");
    return -1;
    }
    if((pid = fork()) == 0)
    {// chile process
    int fd2[2];
    if(pipe(fd2))
    {
    printf("pipe2 error\n");
    return -1;
    }
    close(1);
    dup2(fd2[1],1);
    close(fd[0]);
    close(fd2[1]);
    system(pCmd);
    read(fd2[0], pResult, maxlen);
    pResult[strlen(pResult)-1] = 0;
    write(fd[1], pResult, strlen(pResult));
    close(fd2[0]);
    exit(0);
    }
    // parent process
    close(fd[1]);
    p = pResult;
    left = maxlen;
    while((count = read(fd[0], p, left))) {
    p = count;
    left -= count;
    if(left == 0)
    break;
    }
    close(fd[0]);
    return 0;
    }
    int main(void)
    {
    char result[1025];
    my_system("LC_ALL=C ifconfig", result, 1025);
    printf("the result is\n\n%s\n", result);
    return 0;
    }


  • 相关阅读:
    插入排序-Java
    选择排序-java
    逻辑回归----梯度上升
    logistic回归----- 随机梯度下降法
    JAVA实现聚类指标的计算Purity、NMI、RI、Precision、Recall、F值。
    Python 条形图绘制
    java中接口的注意事项
    算法-双向队列
    算法-manacher-最长回文子串-1
    算法-kmp-1
  • 原文地址:https://www.cnblogs.com/wangkangluo1/p/2342597.html
Copyright © 2011-2022 走看看