Answer: ‘system()’ function is used to execute SHELL COMMANDS which we can’t use directly in C programs. Note here that program execution doesn’t complete until the COMMAND has completed. This function is defined in ‘stdlib.h’ header and is prototyped as below
int system(char const *COMMAND);
Note that COMMAND is passed as a string. ‘system()’ function, then, passes this COMMAND to the host environment so that it can be executed as a command by the systems’ command processor. To ensure if command processor exists, call system() with NULL argument and check the return value if it’s non-zero. Let’s work with a simple C program to see how ‘system()’ works on Linux Machine.
/* system.c -- program calls system() to execute SHELL COMMANDS */ #include <stdio.h> #include <stdlib.h> #include <assert.h> int main(void) { int status; /* assert if command processor is available */ assert((system(NULL)) != 0); /* let's attempt to execute SHELL commands */ system("ls -l"); /* do some more processing here */ exit(0); }
Try to execute above program and observe the output! Notice that ‘assert()’ function ensures if command processor is available.
Sanfoundry Global Education & Learning Series – 1000 C Tutorials.
- Get Free Certificate of Merit in C Programming
- Participate in C Programming Certification Contest
- Become a Top Ranker in C Programming
- Take C Programming Tests
- Chapterwise Practice Tests: Chapter 1, 2, 3, 4, 5, 6, 7, 8, 9, 10
- Chapterwise Mock Tests: Chapter 1, 2, 3, 4, 5, 6, 7, 8, 9, 10
- Apply for Computer Science Internship
- Practice BCA MCQs
- Practice Computer Science MCQs
- Buy C Books
- Watch Advanced C Programming Videos