14.4k views
2 votes
- Create a program(forkchildren.c) that will fork off two children.

- One child will run the "Is -I" command.
- The other will run "cat forkchildren.c".
- The main program will wait for the children to finish and then print a note saying it is finished and then it will end.
- No pipe is needed for this assignment, each child is separate.
- Please submit an image of the code and the output in a Word document.

1 Answer

5 votes

Final answer:

The question involves writing a C program for UNIX-based systems that creates two child processes using fork(), where one executes 'ls -l' and the other 'cat forkchildren.c', while the parent waits for both to finish before it prints a message and terminates.

Step-by-step explanation:

The subject of the question involves creating a program in C on a UNIX-based system that utilizes system calls like fork() and exec() to create child processes. The goal is to have one child process execute the ls -l command and the other to display the contents of the forkchildren.c file, with the parent process waiting for both to finish. The following code snippet demonstrates how to achieve this:

#include
#include
#include
#include

int main() {
int status;
pid_t pid1, pid2;
pid1 = fork();
if (pid1 == 0) {
// First child process
execlp("ls", "ls", "-l", NULL);
} else {
pid2 = fork();
if (pid2 == 0) {
// Second child process
execlp("cat", "cat", "forkchildren.c", NULL);
}
}
// Parent process
waitpid(pid1, &status, 0);
waitpid(pid2, &status, 0);
printf("Parent process is finished.\\");
return 0;
}

Note that the code must be compiled and run on a UNIX-based operating system to work effectively. Each fork() call creates a new process. The first child process executes ls -l using execlp(), while the second child uses the same function to run cat forkchildren.c. The parent process then uses waitpid() for synchronization, waiting for both children to exit before printing its message and terminating.

User Malkam
by
8.6k points

No related questions found