How to use a C program to run a command on terminal?

Solution 1:

you could use the system() function available in stdlib.h to run commands.

DESCRIPTION

system() executes a command specified in string by calling /bin/sh -c string, and returns after the command has been completed. During execution of the command, SIGCHLD will be blocked, and SIGINT and SIGQUIT will be ignored.

You could read more about it over here http://linux.about.com/library/cmd/blcmdl3_system.htm

Solution 2:

Hello i will write for you an example code, explain it to you and really hope this helps you. the function's prototype is something like:

int system(const char* cmd);

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

#define MAX_CMN_LEN 100

int main(int argc, char *argv[])
{
    char cmd[MAX_CMN_LEN] = "", **p;

    if (argc < 2) /*no command specified*/
    {
        fprintf(stderr, "Usage: ./program_name terminal_command ...");
        exit(EXIT_FAILURE);
    }
    else
    {
        strcat(cmd, argv[1]);
        for (p = &argv[2]; *p; p++)
        {
            strcat(cmd, " ");
            strcat(cmd, *p);
        }
        system(cmd);
    }

    return 0;
}

1). open up a terminal and compile the program

2). run it (for example in Ubuntu) ./program_name comman_name -anything - anything

example: ./a.out locale -a

this example prints all locales supported by my compiler which is gcc.

more info:

p is a poniter to pointer to char (like argv is) p = &argv[2], points to -anything string i cat all -anythings to my cmd string i quit the loop when *p points to NULL look at this: -> i will use this symbol to say points to (dont confuse it with right arrow selection operator).

argv[0] -> program_name

argv[1] -> command_name (in this example command name will be locale, but enter the command you want to check instead)

argv[2] -> -anything (in this example -a, which is all locales)

argv[3] -> NULL (in this example, this quits the loop)

ok thats it, i think.