目录
一、system函数
作用:调用其他程序。
#include <stdlib.h>
int system(const char *command);
##const char *command 程序调用命令字符串
##system()函数的返回值如下:
##成功则返回进程状态码
##当sh不能执行时,返回127
##失败返回-1
#include <stdlib.h>
#include <unistd.h>
int main(void)
{
printf("before execl\n");
char *argv[]={"ps",NULL,NULL};
if(system("ps") == -1)//调用system执行ps命令
{
printf("execl failed!\n");
perror("why");
}
printf("after execl\n");
return 0;
}
成功调用ps程序,而且相对于exec函数,system还会继续执行下面的代码。
二、popen函数
作用:调用其他程序。
比system在应用中的好处:以获取运行的输出结果
#include <stdio.h>
FILE *popen(const char *command, const char *type);
##返回值:文件流
##const char *command :运行程序的命令字符串
##const char *type :执行权限,r或w
##如果 type 是 “r” 则文件指针连接到 command 的标准输出;
##如果 type 是 “w” 则文件指针连接到 ##command 的标准输入。
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
int main(void)
{ FILE *fp;
char str[1024]={0};
fp=popen("ps","r");//命令执行ps,权限r
int nread= fread(str,1,1024,fp);//使用fread读取文件流数据,nread返回读取到的字节
printf("have %d char,context is %s\n",nread,str);//输出字符个数,以及内容
return 0;
}
执行结果: