This example is similar to shell as it (1) creates a child proces, (2) the child process executes the printCh program passing arguments to it, and (3) the parent waits for the child to finish.
Unlike a shell, this program only executes one command (printCh) and instead of printing a prompt after the command finishes, it prints how the child terminated and its exit value if it terminated normally.
1
2 #include <stdio.h>
3 #include <stdlib.h>
4 #include <unistd.h>
5 #include <string.h> // for strerror
6 #include <errno.h> // for errno!
7
8 int main()
9 {
10 // Create a child process to run printCh with command line argument
11 // of C. Should work just like $ printCh C
12 pid_t spid, fpid;
13 char *args[3];
14 int status;
15
16 args[0] = "printCh";
17 args[1] = "C";
18 args[2] = (char *) NULL;
19
20 if ( (spid = fork()) == 0 ) {
21 execvp("printCh", args);
22 printf("Error executing printCh\n");
23 exit(1);
24 }
25 fpid = waitpid(spid, &status, 0);
26
27 if ( fpid < 0 ) {
28 printf("wait error: %s\n", strerror(errno));
29 }
30 if ( WIFEXITED(status) ) {
31 printf("child %d terminated normally with exit value %d\n",
32 fpid, WEXITSTATUS(status));
33 } else {
34 printf("child %d terminated abnormally\n", spid);
35 }
36 return 0;
37 }