system()函数
system函数和exec函数一样,都是执行shell 命令,但是system比较顶,把execl函数封装起来,所以习惯上使用system函数
system函数具体功能是调用windows操作系统下的C语言应用
#include <stdlib.h>
int system(const char *command);
const char *command:参数字符串command为命令名
返回值:
成功,则返回进程的状态值;
当sh不能执行时,返回127;
失败返回-1;
2.函数返回值
(1)=-1:出现错误
(2)=0:调用成功但是没有出现子进程
(3)>0:成功退出的子进程的id
如果system()调用成功则最后会返回执行shell命令后的返回值,但是此返回值也有可能为system()调用/bin/sh失败所返回的127,因此最好能再检查errno来确认执行成功
如果system()在调用/bin/sh时失败则返回127,其他失败原因返回-1。
举例:
#include <stdio.h>
#include <unistd.h>
int main(){
if(system("ps") == -1){ //调用ps应用
printf("system filed!\n");
perror("why");
}
printf("Execute after failure!\n");
return 0;
}
执行结果:
3.popen()函数
1.popen()可以执行shell命令,并读取此命令的返回值;
2.p open函数 比system在实际应用中的好处:可以获得运行的输出结果。
3 .popen()函数通过创建一个管道,调用fork()产生一个子进程,执行一个shell以运行命令来开启一个进程。可以通过这个管道执行标准输入输出操作。这个管道必须由pclose()函数关闭,必须由pclose()函数关闭,必须由pclose()函数关闭,而不是fclose()函数(若使用fclose则会产生僵尸进程)。
NAME
popen, pclose - pipe stream to or from a process
SYNOPSIS
#include <stdio.h>
FILE *popen(const char *command, const char *type);
const char *command:参数字符串command为命令名
const char *type: 执行文件的权限,如"w"或"r"
#include <stdio.h>
#include <unistd.h>
int main(){
FILE *fp;
char readBuf[1024] = {0};
fp = popen("ps","r"); //调用popen去执行ps,执行结果会流到popen开辟的管道fp当中
int n_read = fread(readBuf,1,1024,fp); //读取fp管道中的内容到readBuf
printf("read n_read %d byte,readBuf = %s\n",n_read,readBuf);
return 0;
}
执行结果: