Skip to content
TheChatArchiveThe Chat Archive
gpt-4o-2024-05-13· OpenAIAi2 WildChat-4.8M (AI2)

Write simple program on C to run command in Linux shell

  1. User

    Write simple program on C to run command in Linux shell

  2. Assistant

    To run a command in the Linux shell from a C program, you can use the system function provided by the standard C library. This function is quite simple to use for basic needs but doesn't offer much control over the process execution or the output.

    Here's an example of a simple C program that runs a command in the Linux shell:

    #include <stdio.h>
    #include <stdlib.h>
    
    int main() {
        // Command to be executed
        const char *command = "ls -l";
    
        // Print the command to be executed
        printf("Executing command: %s\n", command);
    
        // Execute the command
        int result = system(command);
    
        // Check for errors
        if (result == -1) {
            perror("system");
            return EXIT_FAILURE;
        }
    
        // Exit the program
        return EXIT_SUCCESS;
    }
    

    Steps to compile and run the program

    1. Save the code to a file, for example, run_command.c.

    2. Open a terminal and navigate to the directory where the file is saved.

    3. Compile the program using gcc:

      gcc -o run_command run_command.c
      
    4. Run the compiled program:

      ./run_command
      

    This will execute the ls -l command, which lists the files in the current directory in long format.

    Explanation

    • #include <stdio.h>: Includes the standard I/O library so you can use printf to print messages.

    • #include <stdlib.h>: Includes the standard library which provides the system function.

    • const char *command = "ls -l";: Sets the command you want to run.

    • printf("Executing command: %s\n", command);: Prints the command to the standard output so you know which command is being executed.

    • int result = system(command);: Executes the command using the system function.

    • if (result == -1) { perror("system"); return EXIT_FAILURE; }: Checks if the system call failed and prints an error message if it did.

    • return EXIT_SUCCESS;: Indicates that the program completed successfully.

    This simple example uses the system function for its straightforwardness. For more complex needs, such as capturing the output of the command or better error handling, you might want to explore other functions like popen or the exec family of functions (e.g., execvp).