一、system的使用
作用:执行一个shell指令
原型:
NAME
system - execute a shell command
SYNOPSIS
#include <stdlib.h>
int system(const char *command);
参数说明:
command:可执行指令
返回值:
成功,则返回进程的状态值;
当sh不能执行时,返回127;
失败返回-1;
执行指令的两种方式:
1.在终端输入:./a.out
2. sh -c ./a.out
system的作用跟exec一样,是因为system的源码中调用了execl(“/bin/sh”,“sh”,“-c”,cmd,NULL);
实例:用system函数执行date指令
#include <stdlib.h>
#include <stdio.h>
// int system(const char *command);
int main()
{
printf("date is:\n");
system("date");
return 0;
}
~
执行效果:
二、popen的使用
作用:
popen是计算机科学中的进程I/O函数,与pclose函数一起使用,功能是通过创建一个管道,调用 fork 产生一个子进程,执行一个 shell 以运行命令来开启一个进程。
与system不同之处:
popen可以写到一个流文件里,可以获取运行结果。
原型:
#include <stdio.h>
FILE *popen(const char *command, const char *type);
int pclose(FILE *stream);
参数说明:
command:可执行指令
type:参数只能是读或者写中的一种,得到的返回值(标准 I/O 流)也具有和 type 相应的只读或只写类型。如果 type 是 “r” 则文件指针连接到 command 的标准输出;如果 type 是 “w” 则文件指针连接到 command 的标准输入。
返回值:
如果调用 fork() 或 pipe() 失败,或者不能分配内存将返回NULL,否则返回标准 I/O 流。
返回错误:
popen 没有为内存分配失败设置 errno 值。
如果调用 fork() 或 pipe() 时出现错误,errno 被设为相应的错误类型。
如果 type 参数不合法,errno将返回EINVAL。
实例:用system函数执行date指令,并读到buff里
#include <stdio.h>
#include <string.h>
// int system(const char *command);
int main()
{
FILE *fp;
int nread;
char buff[1024];memset(buff,0,sizeof(buff));
fp = popen("date","r");
//size_t fread(void *ptr, size_t size, size_t nmemb, FILE *stream);
nread = fread(buff,1,1024,fp);
printf("read %d byte,buff:%s\n",nread,buff);
pclose(fp);
return 0;
}
执行效果: