Write a C program consisting of 3 processes, that is, one parent process that fo
ID: 3793194 • Letter: W
Question
Write a C program consisting of 3 processes, that is, one parent process that forks 2 child processes.
Each process will print its process ID and its parent’s process ID.
While the first process (P1) will wait for the remaining child processes (P2 and P3) to terminate, they will perform the following: process P2 will execute the ‘ps –ael’ command (using one of the exec() commands, not system()) and process P3 will execute the ‘ls’ command. This should be done using one of the exec() commands, not the system() call.
The results of P2 and P3 will be written to separate files (i.e., P2_file.txt and P3_file.txt).
Explanation / Answer
#include<stdio.h>
#include<errno.h>
#include<sys/types.h>
#include<sys/stat.h>
#include<unistd.h>
#include<fcntl.h>
int main()
{
pid_t chPid = -1;
int rc = -1;
int fd = -1;
//Main process
printf("Main Process - process Id <%d> : parent process Id <%d> ",getpid(),getppid());
chPid = fork();
//First child process
if(chPid == 0){
printf("Child Process 1 - process Id <%d> : parent process Id <%d> ",getpid(),getppid());
// CLose the standard output file
close(1);
fd = open("./P2_file.txt",O_RDWR | O_CREAT | O_TRUNC, S_IRUSR | S_IWUSR);
//The program /bin/ps will write it's output to fd '1' so making fd '1' an alias of the opened file using dup2()
dup2(fd,1);
char* const args[3] = {"/bin/ps","-ael",NULL};
rc = execvp("/bin/ps",args);
if(rc == -1){
perror("Exec error");
return -1;
}
close(fd);
}
else if(chPid > 0){
chPid = fork();
//Second child Process
if(chPid == 0){
printf("Child Process 2 - process Id <%d> : parent process Id <%d> ",getpid(),getppid());
// CLose the standard output file
close(1);
fd = open("./P3_file.txt",O_RDWR | O_CREAT | O_TRUNC, S_IRUSR | S_IWUSR);
//The program /bin/ls will write it's output to fd '1' so making fd '1' an alias of the opened file using dup2()
dup2(fd,1);
char* const args[2] = {"/bin/ls",NULL};
rc = execvp("/bin/ls",args);
if(rc == -1){
perror("Exec error");
return -1;
}
close(fd);
}
else if(chPid > 0){
waitpid(-1,NULL,0);
}
else{
printf("Error: Failed to fork child process ");
return -1;
}
}
else{
printf("Error: Failed to fork child process ");
return -1;
}
return 0;
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.