1.system函数
system的返回值如下:
成功的话,返回进程的状态值;当sh不能执行时,返回127,失败则返回-1
详细请参考精彩博文:
system函数精彩讲解
system函数例子:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
int main()
{
printf("this is system!\n");
if(system("ps") == -1)
{
printf("execl failed!\n");
perror("why");
}
printf("after system!\n");
return 0;
}
结果:
其实system函数是封装好的exec函数,相比之下其实更多人喜欢用system函数。
2.popen函数:
popen函数比system函数在应用中的好处就是可以获取到运行的输出结果。
精彩博文请查看:
popen函数
直接上代码:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
int main()
{
//size_t fread(void *ptr, size_t size, size_t nmemb, FILE *stream);
printf("this is popen!\n");
FILE *fp;
char *readBuf;
int n_read;
int n_lseek;
fp = popen("ps","r");
n_lseek = fseek(fp,0,SEEK_END);
readBuf = (char *)malloc(sizeof(char)*n_lseek+5);
fseek(fp,0,SEEK_SET);
n_read = fread(readBuf,1,1024,fp);
printf("n_read:%d,readBuf:%s\n",n_read,readBuf);
return 0;
}
结果:
学习笔记,仅供参考!