|
CS456 - Systems Programming
Spring 2025
|
Displaying ./code/forkExec/forkExec.c
/*
* This is a sample program that uses fork and exec to execute a file
*
*
* This program will run the nextPowerof2 program in this directory
*
* to compile
* > gcc -o forkExec forkExec.c
*
* to run
* > ./forkexec
*
*/
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/wait.h>
int main(int argc, char **argv){
//no need for a usage statement, no command line args used here
//setting up our arguments
char *args[] = {"nextPowerof2", "54"};
/*
* args[0] = "nextPowerof2"
* args[1] = "54"
* this arg menu is silliar to the argv[] meny
*/
//printing out what we're running
printf("> %s %s\n", args[0], args[1]);
pid_t pid = fork(); // calling fork, store in pid
//check if fork failed, if so: exit the program
if(pid ==-1){
perror("fork failed");
exit(-1);
}
if(pid){
//we are in the parent process
int status;
waitpid(pid, &status, 0); //waiting for process to change state
return 0;
} else {
//we're in the child process
// we need to use a variant of exec to execute our program
// since we basically have command line arguments, we will use the "execv" argument
// execv takes two arguments,
// - string containing the pathname to the program,
// - array of strings containing all the args associated with the program
//
// so for our first argument, we pass in the name of the program which is in args[0]
// and the second argument, we pass in a pointer to the array of arguments
// // i could have just written "args" instead of &args[0] in this case,
// // but suppose i was passing in argv[1] for the pathname, if i had args after that
// // i'd need to pass in &argv[1] for the second argument to execv as that is the address
// // of the pointer to argv[1]
//
execv(args[0], &args[0]);
}
//then we're done!
return 0;
}
|