简介
可以执行shell命令的函数:
- system()
- exec()
- popen()
可以获取命令执行结果的方法: - popen()
- 无名管道
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:
- 为”r”时,则文件指针连接到cmdstring的标准输出,也就是代表指向执行shell命令返回的消息,也可以认为链接到stdout;
- 为”w”时,则文件指针连接到cmdstring的标准输入,也可以认为链接到stdin
- 成功返回cmdstring的终止状态;出错返回
无名管道
使用管道来获取执行shell命令返回的信息,一般流程如下:
- 创建管道
- 使用dup函数复制描述符将shell命令行标准输出绑定到管道的写端
- 从管道的读端读取数据
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.