system
- 功能:执行shell命令
- 原型:
int system(const char *command);
- 参数:
1)const char *command - 惯用法:
a.先fork()
b.让子进程执行一个新的程序
c.父进程等待子进程终止 - DO
#include <func.h>
int my_system(const char* cmd) {
pid_t pid = fork();
switch (pid) {
case -1:
error(1, errno, "fork");
case 0:
// 子进程执行新的可执行程序
execlp("sh", "sh", "-c", cmd, NULL); // sh -c top
// exec失败
error(1, errno, "execlp");
default:
// 父进程
waitpid(pid, NULL, 0);
}
}
int main(int argc, char* argv[]) {
// system("top"); // 执行top命令
my_system("top"); // ps aux | grep top
return 0;
}