Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Fork using exec function to compile and run another program. So what i am trying

ID: 3847049 • Letter: F

Question

Fork using exec function to compile and run another program.

So what i am trying to do is, i want to compile and execute Program1.c file from the child process of Program2.c

This is Program2.c

#include
#include

int main () {
printf ("just one process only ");
printf("calling fork ");
int pid = fork();
if (pid==0) {
printf("I am child process.");

execl("/usr/bin/gcc", "gcc","/home/folder/Program1.c", "-o", "/home/folder/Program1", NULL);
} else if (pid > 0) {
printf("I am parent process. ");
} else {
printf("Error in fork");
}
return 0;
}

This is Program1.c

#include
#include

int main () {
printf ("just one process only ");
printf("calling fork ");
int pid = fork();
if (pid==0) {
printf("I am child process.");

execl("/usr/bin/gcc", "gcc","/home/folder/Program1.c", "-o", "/home/folder/Program1", NULL);
} else if (pid > 0) {
printf("I am parent process. ");
} else {
printf("Error in fork");
}
return 0;
}

This is Program1.c

Explanation / Answer

#include <stdio.h>
#include <sys/types.h>

int main () {
printf ("just one process only ");
printf("calling fork ");
int pid = fork();
if (pid==0) {
printf("I am child process.");
//execv("/usr/bin/gcc", "gcc","/home/akshay/Chegg/Program1.c", "-o", "/home/akshay/Chegg/Program1", NULL);
execv("/bin/echo","/home/akshay/Chegg/Program1.c");

system("/home/akshay/Chegg/Program1");

} else if (pid > 0) {
printf("I am parent process. ");
} else {
printf("Error in fork");
waitpid(pid,0,0); /* wait for child to exit */

}
return 0;
}

===========================================================

Output:

akshay@akshay-Inspiron-3537:~/Chegg$ gcc Program2.c -o Program2
akshay@akshay-Inspiron-3537:~/Chegg$ ./Program2
just one process only
calling fork
I am parent process.
Hello
I am child process.

===========================================================

Program1.c

#include <stdio.h>
#include <sys/types.h>

#define MAX_COUNT 200


void main(void)
{
printf("Hello ");

}

===========================================================

Just wait more time as it may take long time execute code

Let me know if you have any problem.

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote