system,popen函数的使用
#include <stdlib.h>
int system(const char *command);
1 #include <stdio.h>
2 #include <stdlib.h>
3 #include <unistd.h>
4
5
6 int main(void)
7 {
8 printf("before execl\n");
9 // if(execl("/bin/ls","ls",NULL,NULL) == -1)
10 if(system("ps") == -1)
11 {
12 printf("execl failed\n");
13 perror("why");
14 }
15 printf("after execl\n");
16 return 0;
17 }
popen函数的使用,比system的好处可以获取运行输出结果
#include <stdio.h>
FILE *popen(const char *command, const char *type);
int pclose(FILE *stream);
size_t fread(void *ptr, size_t size, size_t nmemb, FILE *stream);
因为要获取还需要用到fread,fread用法返回的是int型,其中*ptr是获取内容后放置的空间,size_t size是一次多少位获取,size_t nmemb获取多少次,FILE *stream是获取的字节流(内容)
1 #include <stdio.h>
2 #include <stdlib.h>
3 #include <unistd.h>
4
5
6 int main(void)
7 {
8 char ret[1024]={0};
9 FILE *fp;
10 fp = popen("ps","r");
11 int nread = fread (ret,1,1024,fp);
12 printf("read ret %d beyt,ret = %s",nread,ret);
13 return 0;
14 }