执行Shell命令与获取命令结果的方法

简介

可以执行shell命令的函数:

  1. system()
  2. exec()
  3. popen()
    可以获取命令执行结果的方法:
  4. popen()
  5. 无名管道

1. system

NAME
       system - execute a shell command

SYNOPSIS
       #include <stdlib.h>

       int system(const char *command);

RETURN VALUE
       The return value of system() is one of the following:

       *  If command is NULL, then a nonzero value if a shell is available, or 0 if no shell is available.
		
       *  If  a child process could not be created, or its status could not be retrieved, the return value
          is -1.

       *  If a shell could not be executed in the child process, then the return value is  as  though  the
          child shell terminated by calling _exit(2) with the status 127.

       *  If  all system calls succeed, then the return value is the termination status of the child shell
          used to execute command.  (The termination status of a shell is the termination  status  of  the
          last command it executes.)

       In  the  last  two cases, the return value is a "wait status" that can be examined using the macros
       described in waitpid(2).  (i.e., WIFEXITED(), WEXITSTATUS(), and so on).

       system() does not affect the wait status of any other children.

2. exec函数簇

调用exec函数时,该调用ecec的进程执行的程序完全替换为新程序,但并不创建新进程,前后进程的ID并不改变。exec只是用磁盘上的一个新程序替换了当前进程的正文段、数据段、堆段和栈段。一般先fork出子进程再做该动作。

3. popen()和pclose()

常见操作是创建一个连接到另一个进程(shell的命令行)的管道,然后读其输出或向其输入端发送数据。
工作原理:popen先执行fork,然后调用exec执行cmdstring,并返回一个标准的I/O文件指针。

NAME
       popen, pclose - pipe stream to or from a process

SYNOPSIS
       #include <stdio.h>

       FILE *popen(const char *command, const char *type);

       int pclose(FILE *stream);
  • cmdstring:包含shell命令字符串
  • type:
    1. 为”r”时,则文件指针连接到cmdstring的标准输出,也就是代表指向执行shell命令返回的消息,也可以认为链接到stdout;
    2. 为”w”时,则文件指针连接到cmdstring的标准输入,也可以认为链接到stdin
  • 成功返回cmdstring的终止状态;出错返回

无名管道

使用管道来获取执行shell命令返回的信息,一般流程如下:

  1. 创建管道
  2. 使用dup函数复制描述符将shell命令行标准输出绑定到管道的写端
  3. 从管道的读端读取数据
SYNOPSIS
       #include <unistd.h>

       int pipe(int pipefd[2]);

       #define _GNU_SOURCE             /* See feature_test_macros(7) */
       #include <fcntl.h>              /* Obtain O_* constant definitions */
       #include <unistd.h>

       int pipe2(int pipefd[2], int flags);
       
RETURN VALUE
       On success, zero is returned.  On error, -1 is returned, and errno is set appropriately.

参考

https://www.cnblogs.com/clovershell/p/12215253.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值