// CS 450: Process example 1: fork, execlp // version 2014-01-21 3:55 PM // #include #include // for fork, execlp #include // wait int main() { pid_t pid; // Process id pid = fork(); // Fork child process // If pid < 0, an error occurred // if (pid < 0) { fprintf(stderr, "Fork Failed\n"); return 1; } // If pid > 0, we're the parent. // Wait for the child to finish // else if (pid > 0) { wait(NULL); fprintf(stderr, "Parent says: Child process %d complete\n", pid ); } // If pid = 0, we're the child. // Execute an ls command and quit // else { fprintf(stderr, "Child says: I'm %d\n", getpid()); int error = execl("/bin/ls", "ls", "-l", NULL); // execl only returns if an error occurs // fprintf(stderr, "Child says: exec returns with error %d\n", error); } return 0; // parent finishes } // Sample output: // // Child says: I'm 1310 // total 40 // -rw-r--r--@ 1 jts jts 734 Jan 21 15:52 Lec03_1_proc.py // -rw-r--r--@ 1 jts jts 820 Jan 22 2013 Lec03_2_proc.c // -rwxr-xr-x 1 jts jts 9036 Jan 21 15:55 a.out // Parent says: Child process 1310 complete