一.system函数
int system(const char *command);
//包含的头文件
#include <stdlib.h>
const char *command:参数字符串command为命令名
返回值:
成功,则返回进程的状态值;
当sh不能执行时,返回127;
失败返回-1;
与execl函数区别:execl调用后子进程函数直接“飞了”,而调用system函数后,还会返回到子进程。
•编程示例
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
int main(void)
{
printf("this pro get system date:\n");
if(system("ps") == -1)
{
printf("execl failed!\n");
perror("why");
}
printf("after execl\n");
return 0;
}
二.popen函数
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"
popen函数比system在应用中的好处:可以获取运行的输出结果。
•编程示例
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
int main(void)
{
char ret[1024] = {0};
FILE *fp;
fp = popen("ps","r");
int n_read = fread(ret,1,1024,fp);
printf("read ret=%d byte,ret=%s\n",n_read,ret);
return 0;
}