目录
1、system()函数
system函数具体功能是调用windows操作系统下的C语言应用
#include <stdlib.h>
int system(const char *command);
const char *command:参数字符串command为命令名
返回值:
成功,则返回进程的状态值;
当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;
}
执行结果:
2、popen()函数
popen()函数通过创建一个管道,调用fork()产生一个子进程,执行一个shell以运行命令来开启一个进程。
popen函数比system在应用中的好处:可以获取运行的输出结果
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;
}
执行结果: