LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Linux - Newbie (https://www.linuxquestions.org/questions/linux-newbie-8/)
-   -   command substitution in linux (https://www.linuxquestions.org/questions/linux-newbie-8/command-substitution-in-linux-814627/)

anu_123 06-16-2010 11:16 PM

command substitution in linux
 
Hello

I am writing a C++ code to get hard disk serial number of the computer.
This can be achieved by the following command in linux as root user

hdparm -I /dev/hda | grep -i Serial

To use this command in C++ i used

system("hdparm -I /dev/hda | grep -i Serial");

after compiling and running the code the output is printed on the console as

Serial Number: S00JJ20X897934

which is correct,

What i want to do is to store this value in a variable and then use that
variable further in my cpp code.Which i am unable to do...

I could substitute that value in a variable using command substitution of linux, as

system("hdd_id=`hdparm -I /dev/hda | grep -i Serial`");

but then had no access to that variable hdd_id in cpp code..
If i do the above without using system and echo $hdd_id i get the required, but cannot use it in cpp code.

Please suggest how to achieve this.

Thanks in advance

Perromuerto 06-17-2010 12:25 AM

Easy. Redirect the output to a transient file like this:
system("hdparm -I /dev/hda | grep -i Serial > /tmp/t123");
Then read the file, and don't forget to erase it.

keithieopia 06-17-2010 12:28 AM

I stink at C++, but I'll give this a shot at answering it. Otherwise, http://stackoverflow.com/ is probably the best place to get a clever answer.

The quick and dirty way would be to simply pipe the command's output to a text file, then use cpp to open and read the output. For instance:
Code:

system("hdparm -I /dev/hda | grep -i Serial > output.txt");
fp = fopen("output.txt", r");
if(fp != NULL){
/* Do stuff */
}

Otherwise, try using IPC: http://beej.us/guide/bgipc/

keithieopia 06-17-2010 12:31 AM

Perromuerto beat me to it. The IPC stuff is still relevant though.


All times are GMT -5. The time now is 12:35 AM.