Calling a shell script from a C program

Hi,

I have a shell script which connects to a database and fetches the count of the records from a table. I want to embed this whole script in a C program. Also the count fetched should be available in the C program for further usage.

Please let me know how this can be done.

Thanks

Start it using man popen (POSIX), and read from the returned file descriptor as you would from any other.

Hi pludi,

can you show me how it's done with a sample snippet please?

hello

You need system() function to call scripts or other commands. you can use "wc" command to count the number of records returned by it.

Regards,
Gaurav.

Quick example, will copy the contents of the files given on the command line to stdout, prefixed by the filename and the line number (yes, it's UUOC):

#include <stdio.h>

int main(int argc, char **argv)
{
    FILE *pipe = NULL;
    int i;
    char buffer[1024];

    if (argc == 1) {
        return 1;
    }
    for (i = 1; i < argc; i++) {
        sprintf(buffer, "cat -n %s", argv);
        if ((pipe = popen(buffer, "r")) == NULL) {
            perror("popen");
            return 1;
        }
        while (fgets(buffer, 1024, pipe) != NULL)
            printf("%s: %s", argv, buffer);
        if (pclose(pipe) == -1) {
            perror("pclose");
            return 1;
        }
    }
    return 0;
}

Hi Gaurav,

below is the system call that I have used to call my shell script named "test"

#include <stdio.h>
#include <stdlib.h>

int main()
{

int i;

i=system("./test 1234");
printf("i=%d\n",i);

}

Here "test" is the shell script that is fetching the count from a table for a particular column("1234") that I am passing as the parameter. When the "test" script alone is run, it is returning the correct count but when trying to check through the C program it's returning some different value. How can I get the exact value from the script in my program above? wc is returning 1 as it's a single line output but I want the actual count value.

Can you help?

Because system() does not return the output of a script, but only the exit status. Eg. if instead of "./test" you'd run /bin/true (or /usr/bin/true), you'd always get 0, while with /bin/false you'd always get 1. If you want to get the output of a command, either use a temporary file, or popen as in the example I've given.

thanks for the clarification pludi. so, does popen only take a command or can an entire script be passed in. can you show me how my test script fits in your example please?

or a fifo.

Regards,
Gaurav.

From the man page of man popen (POSIX)

So any program you could call using

sh -c "/path/to/program arg1 arg2 ... argn"

can be called just the same.

Also, please make it a habit of reading the man pages first when available, experiment a bit for yourself, and ask specific questions. We're here to help you, not to do your work for you.