头文件:
#include <stdio.h>
函数定义:
FILE * popen ( const char * command , const char * type );
int pclose ( FILE * stream );
popen() 函数通过创建一个管道,调用 fork 产生一个子进程,在shell中执行“command ”命令来开启一个进程。
这个进程必须由 pclose() 函数关闭,而不是 fclose() 函数。
pclose() 函数关闭标准 I/O 流,等待命令执行结束,然后返回 shell 的终止状态。
如果 shell 不能被执行,则 pclose() 返回的终止状态与 shell 已执行 exit 一样。
参数:
这个进程必须由 pclose() 函数关闭,而不是 fclose() 函数。
pclose() 函数关闭标准 I/O 流,等待命令执行结束,然后返回 shell 的终止状态。
如果 shell 不能被执行,则 pclose() 返回的终止状态与 shell 已执行 exit 一样。
参数:
type : 只能是读或者写中的一种,得到的返回值(标准 I/O 流)也具有和 type 相应的只读或只写类型。
--- 如果 type 是 "r" 则文件指针连接到 command 的标准输出;
--- 如果 type 是 "w" 则文件指针连接到 command 的标准输入。
--- 如果 type 是 "r" 则文件指针连接到 command 的标准输出;
--- 如果 type 是 "w" 则文件指针连接到 command 的标准输入。
command :是一个指向以 NULL 结束的 shell 命令字符串的
指针。这行命令将被传到 bin/sh 并使用-c 标志,shell 将执行这个命令。
返回值:
popen返回值是个标准 I/O 流,必须由 pclose 来终止。
如果调用 fork() 或 pipe() 失败,或者不能分配内存将返回NULL,否则返回标准 I/O 流。
前面提到这个流是单向的。
所以向这个流写内容相当于写入该命令的标准输入;命令的标准输出和调用 popen 的进程相同。
与之相反的,从流中读数据相当于读取命令的标准输出;命令的标准输入和调用 popen 的进程相同。
使用方法:
popen返回值是个标准 I/O 流,必须由 pclose 来终止。
如果调用 fork() 或 pipe() 失败,或者不能分配内存将返回NULL,否则返回标准 I/O 流。
前面提到这个流是单向的。
所以向这个流写内容相当于写入该命令的标准输入;命令的标准输出和调用 popen 的进程相同。
与之相反的,从流中读数据相当于读取命令的标准输出;命令的标准输入和调用 popen 的进程相同。
if((fp=popen("/usr/bin/uptime","r"))==NULL);
{
sprintf(buf,"error: %s\n", strerror(errno));
....//异常处理
}
else
{
....
pclose(fp);
}
例1:
vim popen2.c
#include <stdio.h>
#include <string.h>
#include <strings.h>
int main(){
FILE *file_pipe;
unsigned char string[32];
int i,j,pos,len;
unsigned int partition_num;
memset(string,0x00,sizeof(string));
/* get the number of partition */
file_pipe=popen("ls -l /dev/sda? |grep \"sda\" -c","r");
if(NULL==file_pipe){
printf("Failed to retrive the partition information.\n");
return -1;
}
fgets(string,sizeof(string),file_pipe);
pclose(file_pipe);
printf("string = %s\n",string);
memset(string,0x00,sizeof(string));
partition_num=atoi(string);
printf("partition_num = 0x%x\n", partition_num);
/*detect the detail partiton infomation.*/
sprintf(string,"/dev/sda%d",partition_num-2);
printf("string2 = %s\n",string);
return 0;
}
输出:
$ ./a.out
string = 3
partition_num = 0x3
string2 = /dev/sda1
例2 :
#include <stdio.h>
#include <string.h>
#define _LINE_LENGTH 300
int get_path_total(const char *path, long long* total) {
int err=-1;
FILE *file;
char line[_LINE_LENGTH];
char *p;
char tmp[100];
char *token;
sprintf(tmp, "df %s", path);
file = popen(tmp, "r");
if (file != NULL) {
if (fgets(line, _LINE_LENGTH, file) != NULL) {
if (fgets(line, _LINE_LENGTH, file) != NULL) {
token = strtok(line, " ");
if (token != NULL) {
printf("token 1 = %s\n", token);
}
token = strtok(NULL, " ");
if (token != NULL) {
printf("token 2 = %s\n", token);
*total=atoll(token)/1024; /* k/1024 */
err=0;
}
}
}
pclose(file);
}
return err;
}
int main()
{
char *path = "/dev";
long long total;
get_path_total(path, &total);
printf("total = %lld KB\n", total);
return 0;
}
输出:
$ ./a.out
token 1 = udev
token 2 = 1999588
total = 1952 KB