Hi have want to create C program where its a dealing with pr
Hi have want to create C program where its a dealing with processes using fork. Where one is the parent, and it will be fork 2 other processes as its children. So basically one parent process will have two children processes. All the processes will print out a (process ID) and also its parent\'s ID. Also the parent process will wait until both the children have be ended or terminated. The two children will also execute some command and write to a text file. Using exec() commands, the children processes will do as given below:
Child 1: will perform command \"ps -ejH\" and the result will write to a file called \"child1.txt\"
Child 2: will perform command \"ls\" and the result will write to a file called \"child2.txt\"
Also create a diagram for the program: Example shown below
Code:
#include <sys/types.h>
#include <stdio.h>
#include <unistd.h>
int main()
{
pid t pid;
/* fork a child process */
pid = fork();
if (pid < 0) { /* error occurred */
fprintf(stderr, \"Fork Failed\");
return 1;
}
else if (pid == 0) { /* child process */
execlp(\"/bin/ls\",\"ls\",NULL);
}
else { /* parent process */
/* parent will wait for the child to complete */
wait(NULL);
printf(\"Child Complete\");
}
return 0;
}
Solution
#include <sys/types.h>
#include <stdio.h>
#include <unistd.h>
#include <fcntl.h>
int main()
{
int pid;
/* fork a child process */
int fd1, fd2;
pid = fork();
if (pid < 0) { /* error occurred */
fprintf(stderr, \"Fork Failed\");
return 1;
}
if (pid == 0) { /* child process */
printf(\"chile1 process Id : %d\",getpid() );
close(1); /* close the stdout */
/* fd-file descriptor, childe1.txt will create if does not exist and open in read & write if exist */
fd1 = open(\"child1.txt\", O_WRONLY|O_TRUNC|O_CREAT, 0644);
execlp(\"/bin/ps\", \"ps\", \"-ejH\", NULL);
printf(\"\ \");
}
else {
if(fork()==0){
printf(\"\ \");
printf(\"chile2 process Id : %d\",getpid() );
close(1); // close the stdout fd
fd2 = open(\"child2.txt\", O_WRONLY|O_TRUNC|O_CREAT, 0644);
execlp(\"/bin/ls\",\"ls\",NULL);
printf(\"\ \");
}
else{
/* parent process */
/* parent will wait for the child to complete */
wait(0);
printf(\"Child Complete\ parent process id :%d\ \", getppid());
}
}
return 0;
}

