First of all, yes this is a laboratory activity in my class, but I have already submitted and defended this exercise. What I would like to know is if there is another way, a more efficient way to write this code.
What we were tasked to do was to write a code that creates a process, which creates a child, which in turn creates another child and finally creates a another child.
*edit: I separated and numbered the requirements for better readability :)
The last child would show the current processes running in the system.
Its parent would then ask for a word then create a file using the input by the user.
Its parent would then ask for a word or a phrase, then find it within the libraries in your machine (Let's say I typed hi, it should find and list the files containing hi & its directory. The position of the word hi should not matter)
Lastly, the main parent would just print its parent id.
Here is my complete code for that matter:
int main(void){
char fileName[30];
char phrase[30];
int pid = fork();
int fd[2];
pipe(fd);
if(pid==0){
printf ("CHILD1: I am the 1st child\n");
printf ("CHILD1: ID is %d \n", getpid());
printf ("CHILD1: Parent ID is %d \n", getppid());
int pid2 = fork();
if(pid2==0){
printf ("\t CHILD2: I am the 2nd child\n");
printf ("\t CHILD2: ID is %d \n", getpid());
printf ("\t CHILD2: Parent ID is %d \n", getppid());
int pid3 = fork();
if(pid3==0){
printf ("\t\t CHILD3: I am the 3rd child\n");
printf ("\t\t CHILD3: ID is %d \n", getpid());
printf ("\t\t CHILD3: Parent ID is %d \n", getppid());
execlp ("/usr/bin/top", "top", NULL);
}else if(pid3==-1){
printf ("ID is %d", getpid());
printf ("error");
exit(1);
}else{
wait(NULL);
printf ("\t CHILD2: Enter a filename: ");
scanf ("%s", fileName);
printf ("\t CHILD2: %s was succcessfully created!\n", fileName);
execlp ("/bin/touch", "touch", fileName, NULL);
}
}else if(pid2==-1){
printf ("ID is %d", getpid());
printf ("error");
exit(1);
}else{
wait(NULL);
int pid4 = fork();
if(pid4 > 0) {
printf ("CHILD1: Enter a pharse: ");
scanf ("%s", phrase);
close(fd[1]);
close(STDIN_FILENO);
dup2(fd[0],STDIN_FILENO);
execlp ("/bin/grep", "grep", phrase, NULL);
}else if (pid4 == 0) {
close(fd[0]);
close(STDOUT_FILENO);
dup2(fd[1],STDOUT_FILENO);
execlp ("/usr/bin/find", "find", NULL);
}else {
printf ("error");
}
}
}else if(pid==-1){
printf ("ID is %d", getpid());
printf ("error");
exit(1);
}else{
wait(NULL);
printf ("PARENT: I am the parent\n");
printf ("PARENT: ID is %d \n", getpid());
}
}