Write simple program on C to run command in Linux shell
- User
Write simple program on C to run command in Linux shell
- Assistant
To run a command in the Linux shell from a C program, you can use the
systemfunction 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
-
Save the code to a file, for example,
run_command.c. -
Open a terminal and navigate to the directory where the file is saved.
-
Compile the program using
gcc:gcc -o run_command run_command.c -
Run the compiled program:
./run_command
This will execute the
ls -lcommand, which lists the files in the current directory in long format.Explanation
-
#include <stdio.h>: Includes the standard I/O library so you can useprintfto print messages. -
#include <stdlib.h>: Includes the standard library which provides thesystemfunction. -
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 thesystemfunction. -
if (result == -1) { perror("system"); return EXIT_FAILURE; }: Checks if thesystemcall failed and prints an error message if it did. -
return EXIT_SUCCESS;: Indicates that the program completed successfully.
This simple example uses the
systemfunction 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 likepopenor theexecfamily of functions (e.g.,execvp). -