popen

The popen() function shall execute the command specified by the string command. It shall create a pipe between the calling program and the executed command, and shall return a pointer to a stream that can be used to either read from or write to the pipe.

EXAMPLES

Using popen() to Obtain a List of Files from the ls Utility

The following example demonstrates the use of popen() and pclose() to execute the command ls * in order to obtain a list of files in the current directory:

#include <stdio.h>
...


FILE *fp;
int status;
char path[PATH_MAX];


fp = popen("ls *", "r");
if (fp == NULL)
    /* Handle error */;


while (fgets(path, PATH_MAX, fp) != NULL)
    printf("%s", path);


status = pclose(fp);
if (status == -1) {
    /* Error reported by pclose() */
    ...
} else {
    /* Use macros described under wait() to inspect `status' in order
       to determine success/failure of command executed by popen() */
    ...
}

execute the command **grep ‘processor’ /proc/cpuinfo sort -u wc -l**
int get_processor_num()
{
	FILE *fstream=NULL;
	char buff[1024];
	memset(buff,0,sizeof(buff));
	if(NULL==(fstream=popen("grep 'processor' /proc/cpuinfo | sort -u | wc -l","r")))
	{
	    return -1;
	}

	fgets(buff, sizeof(buff), fstream);
	printf("%s", buff);
	
	pclose(fstream);
	return 0;
}