i have a c program that runs following command:
system("sudo grep '' /sys/class/dmi/id/board_*")
and give output on command line.
I want the output to be stored in some variable in c program, so that i can filter board_serial.
Take a look at popen. Here is a simple example of how you could use it to capture the program output:
#include<stdio.h>
int main()
{
FILE *p;
p = popen("ls -l", "r");
if(!p) {
fprintf(stderr, "Error opening pipe.\n");
return 1;
}
while(!feof(p)) {
printf("%c", fgetc(p));
}
if (pclose(p) == -1) {
fprintf(stderr," Error!\n");
return 1;
}
return 0;
}
But, it looks like you just want to read some value from a file, am I right? I would prefer to just open (fopen()) the files which have the values inside and read those values to variables in my C program. Try something like this (just a simple example):
#include<stdio.h>
#include<stdlib.h>
#define MAX 100
int main()
{
FILE *fp;
char result[MAX];
int i;
char c;
fp = fopen("/sys/class/dmi/id/board_name", "r");
if(!fp) {
fprintf(stderr, "Error opening file.\n");
return 1;
}
i = 0;
while((c = fgetc(fp)) != EOF) {
result[i] = c;
i++;
}
result[i] = '\0';
printf("%s", result);
i = atoi(result);
printf("%d", i);
if (fclose(fp) == -1) {
fprintf(stderr," Error closing file!\n");
return 1;
}
return 0;
}
Easiest way is to redirect the output to a file and the read that file for parsing the output.
system("sudo grep '' /sys/class/dmi/id/board_* 1>out.txt 2>err.txt");
fd_out = fopen("out.txt", "r");
fd_err = fopen("err.txt", "r");
Or you can use popen function.
fd_out = popen("sudo grep '' /sys/class/dmi/id/board_*", "r");
fopen() and simply read its contents to a variable. It looks like the user just wants to read a file.Yes popen is definitely the best choice. Have a look here
http://www.yolinux.com/TUTORIALS/ForkExecProcesses.html
grep '' /sys/class/dmi/id/board_*? Or did you intentionally leave out your search string? If that's really what you're doing,cat /sys/class/dmi/id/board_*would be better. Or better yet, justfopen()each file (although you would have to handle the wildcard bit yourself then, which is one "benefit" of using thesystem()approach).