#1
  1. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Jun 2003
    Posts
    245
    Rep Power
    11

    Converting bash code to C code


    To run a bash comand within a C program, I would use

    1) system ("ifconfig") or
    2) f = popen ("ifconfig", "r") or
    3) execlp ("bin/bash", "bash", "-c", linux_command, (char*)0);

    The problem with the bash code below is they are too long to be put in a string and then execute it using one of the three method above.

    How would I write the code below in C. Most critical is
    1) What command to use to read (detect) from hda to hdz
    2) I guess the bash command if [ -a /proc/ide/$i ] is short enough
    to be used in one of the three method above.
    3) As for the command hdparm -c1 -d1 -m16 /dev/$i > /dev/null
    one of the three method above would do.
    ===========================================

    #!/bin/bash

    for i in hda hdb hdc hdd hde hdf hdg hdh hdi hdj hdk hdl hdm hdn hdo hdp hdq hdr hds hdt hdu hdv hdw hdx hdy hdz
    do
    if [ -a /proc/ide/$i ]
    then
    hdparm -c1 -d1 -m16 /dev/$i > /dev/null
    fi
    done
  2. #2
  3. Banned ;)
    Devshed Supreme Being (6500+ posts)

    Join Date
    Nov 2001
    Location
    Woodland Hills, Los Angeles County, California, USA
    Posts
    9,595
    Rep Power
    4207
    Something like this maybe:
    Code:
    #include <sys/types.h>
    #include <sys/stat.h>
    #include <unistd.h>
    #include <stdlib.h>
    #include <stdio.h>
    
    int main(void)
    {
      struct stat sb;
      char buf[4]="hda";
      char path[100];
      char c;
      char cmd[100];
    
      for (c='a'; c <='z'; c++) {
        buf[2] = c;
        sprintf(path, "/proc/ide/%s", buf);
        if (stat(path, &sb) == 0) {
          sprintf(cmd, "hdparm -c1 -d1 -m16 /dev/%s > /dev/null", buf);
          system(cmd);
        }
      }
      return 0;
    }
    Hope this helps :)
  4. #3
  5. /(bb|[^b]{2})/

    Join Date
    Nov 2001
    Location
    Somewhere in the great unknown
    Posts
    5,163
    Rep Power
    792
    Actually, the above bash code is part of an executable bash file. This file is what you would/could call instead of the bash code itself.
    You don't call actual bash code from inside of a C program, you call executables/programs.
    Bash scripts are made executable through thier permissions, but if you try and call bash code from inside a C program you will not usually get the response back that you expect.

IMN logo majestic logo threadwatch logo seochat tools logo