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.
- Check Computer Science Books
- Apply for C Internship
- Check C Books
- Practice Computer Science MCQs
- Practice BCA MCQs