Linux下的C语言#执行系统命令


=Start=

缘由:

整理学习在进行Linux下C编程中碰到的一些知识点,方便以后进行参考。

正文:

参考解答:
在C程序中执行/调用系统命令方法小结:
  • fork+exec #终极方法
  • popen #(额外引入shell进行执行,相当于是「sh -c」)可以获取执行结果,但是是单向的(要么输入,要么输出);如果需要双向的,可以使用底层一点的pipe
  • system #(额外引入shell进行执行,相当于是「sh -c」)只是执行/调用,但无法获取执行结果
#include <stdio.h>
int main() {
    FILE * f = popen( "ls -al""r" );
    if ( f == 0 ) {
        fprintf( stderr, "Could not execute\n" );
        return 1;
    }
    const int BUFSIZE = 1000;
    char buf[ BUFSIZE ];
    while( fgets( buf, BUFSIZE,  f ) ) {
        fprintf( stdout, "%s", buf  );
    }
    pclose( f );
}

&

#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
 
int main()
{
    const int BUFSIZE = 1000;
    FILE *read_fp = NULL;
    FILE *write_fp = NULL;
    char buffer[BUFSIZE + 1];
    int chars_read = 0;
 
    // 初始化缓冲区
    memset(buffer, '\0', sizeof(buffer));
     
    // 打开ls和grep进程
    read_fp = popen("ls -l""r");
    write_fp = popen("grep rwxrwxr-x""w");
     
    // 两个进程都打开成功
    if (read_fp && write_fp)
    {
        // 读取一个数据块
        chars_read = fread(buffer, sizeof(char), BUFSIZE, read_fp);
        while (chars_read > 0)
        {
            buffer[chars_read] = '\0';
             
            // 把数据写入grep进程
            fwrite(buffer, sizeof(char), chars_read, write_fp);
             
            // 还有数据可读,循环读取数据,直到读完所有数据
            chars_read = fread(buffer, sizeof(char), BUFSIZE, read_fp);
        }
         
        // 关闭文件流
        pclose(read_fp);
        pclose(write_fp);
         
        exit(EXIT_SUCCESS);
    }
     
    exit(EXIT_FAILURE);
}
参考链接:

Linux下使用popen()执行shell命令
http://www.cnblogs.com/caosiyang/archive/2012/06/25/2560976.html

http://man7.org/linux/man-pages/man3/popen.3.html
http://blog.csdn.net/dlutbrucezhang/article/details/8840329

https://stackoverflow.com/questions/16127027/linux-command-executing-by-popen-on-c-code

https://stackoverflow.com/questions/671461/how-can-i-execute-external-commands-in-c-linux

Can popen() make bidirectional pipes like pipe() + fork()?
https://stackoverflow.com/questions/3884103/can-popen-make-bidirectional-pipes-like-pipe-fork

kill a process started with popen
https://stackoverflow.com/questions/548063/kill-a-process-started-with-popen

what is the difference between popen() and system() in C
https://stackoverflow.com/questions/8538324/what-is-the-difference-between-popen-and-system-in-c

Linux进程间通信(三):匿名管道 popen()、pclose()、pipe()、close()、dup()、dup2()
http://www.cnblogs.com/phpgo/p/5817818.html

=END=

, ,

《 “Linux下的C语言#执行系统命令” 》 有 3 条评论

发表回复

您的电子邮箱地址不会被公开。 必填项已用 * 标注