Question
(If you are working on my previous question, don't bother. I figured it out. You can charge me for two questions if you can help
(If you are working on my previous question, don't bother. I figured it out. You can charge me for two questions if you can help ma fix this part.)
I am programming in C using VIM and terminal under Ubuntu Linux. I have been working on this code to do a fork when my program receives a system command. The it should call execvp() and hand off the task to the system. I have no idea how to use a fork and the assignment is almost due.
The instructions say executing external programs: call fork(), execvp() and waitpid() and always check the return code from each to report any errors. If an error occurs in execvp(), exit the process with exit (0) after issuing an error message.
The following code is in an else statement which only runs if the user makes a call to the system. This is what I have so far. I may have skipped a { or two.
int rc; int status; char *cmd; char *myArgv[3];
if (argc > 1) { cmd = argv[1]; myArgv[ 0 ] = cmd; myArgv[ 1 ] = argv[ 2 ]; myArgv[ 2 ] = NULL; }
else { cmd = "ls"; myArgv[ 0 ] = cmd; myArgv[ 1 ] = "-al"; myArgv[ 2 ] = NULL; }
printf("Parent: I am pid %d ", getpid() );
rc = fork();
if (rc > 0) { // I am the parent printf("Parent: waiting on pid %d ", rc); waitpid(rc, &status, 0); printf("Parent: child has ended with status %d ", WEXITSTATUS(status)); cmdExit(myArgc, myArgv); } else if (rc == 0) { // I am the child printf("Child: I am pid %d about to exec() %s ", getpid(), cmd); execvp(cmd, myArgv); errno=EINVAL; perror("Child: execvp() failed"); printf("Child: execvp() failed...exiting "); exit(1); } else { // an error occured, no child created errno=EINVAL; perror("Parent: a bad thing happened:"); exit(1); }
}
Step by Step Solution
There are 3 Steps involved in it
Step: 1
Get Instant Access to Expert-Tailored Solutions
See step-by-step solutions with expert insights and AI powered tools for academic success
Step: 2
Step: 3
Ace Your Homework with AI
Get the answers you need in no time with our AI-driven, step-by-step assistance
Get Started