Hello, i am working on a fork() program with child and parent processes. Below i
ID: 3671251 • Letter: H
Question
Hello, i am working on a fork() program with child and parent processes. Below is my current program. My question is what can i do to have the last child process exit correctly. Any help getting this last bug would be greatly appreciated!
My program so far:
#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
#include <sys/wait.h>
int main(){
pid_t myprocessid, child_pid, getpid();
int mystatus;
myprocessid = getpid();
printf("Parent : pid %d. forked", myprocessid);
child_pid = fork();
if (child_pid == 0)
{
printf("Child1 number 0 with pid: %d. exec'd at ", myprocessid);
myprocessid = getpid();
printf("Child2: getpid2() with pid %d. ", getpid());
child_pid = fork();
if ( child_pid == 1)
{
perror("error while fork");
return 1;
}
else if (child_pid == 0)
{
printf("Child3 from parent with pid: %d. ", myprocessid);
myprocessid = getpid();
printf("Child3: pid %d. exec'd ", getpid());
sleep(30);
return 12;
}
else
return 15;
}
else if(child_pid == 1)
{
while ( waitpid(child_pid, &mystatus, WNOHANG) == 0 )
sleep(1);
if ( WIFEXITED(mystatus) )
printf("Child1: Child2 exited with exit status %d. ",WEXITSTATUS(mystatus));
else
printf("Child1: child hasn't ended correctly. ");
}
else {
printf("Parent: pid: %d forked", child_pid);
wait(&mystatus);
if ( WIFEXITED(mystatus))
printf("Parent: child has %d with exit normally ",WEXITSTATUS(mystatus));
else
printf("Parent: child hasn't ended correctly. ");
}
return 0;
}
Explanation / Answer
#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
#include <sys/types.h>
#include <sys/wait.h>
int main(int argc, char * argv[]){
//arguments for ls, will run: ls -l /bin
char * ls_args[4] = { "ls", "-l", "/bin", NULL} ;
pid_t c_pid, pid;
int status;
c_pid = fork();
if (c_pid == 0){
/* CHILD */
printf("Child: executing ls ");
//execute ls
execvp( ls_args[0], ls_args);
//only get here if exec failed
perror("execve failed");
}else if (c_pid > 0){
/* PARENT */
if( (pid = wait(&status)) < 0){
perror("wait");
_exit(1);
}
printf("Parent: finished ");
}else{
perror("fork failed");
_exit(1);
}
return 0; //return success
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.