/* * ISA 563, Spring 2011 * Copyleft by Muhammad Abdulla */ #include #include #include #include #include /* * fork_exec.c -- demonstrate the fork system call, and command execution procedures. */ int main ( int argc, char *argv[] ) { int status; // get child execution status const char *path = "/bin/ls"; // prepare an array of arguments to be passed to execv system call (executed by child) char *args[] = { "ls", // name of command to be executed "/", // ls target "-l", // arguments: -l for long options "-a", // -a for all (list hidden files also) "-S", // -S for sort "--color", // make it colorful NULL // end of }; pid_t pid; pid = fork(); if ( pid < 0 ) { // error condition fprintf(stderr, "Could not fork!\n"); exit(-1); } else if ( pid == 0 ) { // child process execv(path, args); } else { // parent process waitpid(pid, &status, 0); fprintf(stdout, "child exitted with code %d\n", status); } return 0; }