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

Program to be written in C: Write a program to offer a list of several functions

ID: 3849801 • Letter: P

Question

Program to be written in C:

Write a program to offer a list of several functions. When your program is started, show a menu of three functions as follows:

1. Hello World!

2. List files

3. Exit

Please select:

After the user makes his choice by typing the index of the function, your program should read the user input into a 1024-byte buffer, and then execute the corresponding function.

1. If the user input is 1, create a new process with fork()and print out Hello World! in the child process. The parent process should wait for its child process to complete. Then reprint the menu and ask the user for choice.

2. If the user input is 2, create a new process with fork() and run “ls” in the child process to list all the files in the current directory. The parent process should wait for its child process to complete. Then reprint the menu and ask the user for choice.

3. If the user input is 3, the program terminates.

4. If the user input is not 1, 2, or 3, print out an error message, reprint the menu and ask the user for choice.

Here is a sample execution on a Linux machine:

1. Hello World!

2. List files

3. Exit

Please select: 1

Hello World!

1. Hello World!

2. List files

3. Exit

Please select: 2

file1 file2 file3

1. Hello World!

2. List files

3. Exit

Please select: 4

Invalid choice!

1. Hello World!

2. List files

3. Exit

Please select: 3

Explanation / Answer

# include <cctype>
# include <string>
# include <stdio.h>
# include <sys/types.h>
# include <unistd.h>
# include <stdlib.h>
# include <signal.h>

//This below function call will print the ls -l list of all files
void printls()
{
   pid_t child_pid = -1 ; //Global
   child_pid = fork();
   if(child_pid==0)
   {
       excel("/bin/ls","ls","-l",NULL);
   }
   kill(child_pid, SIGKILL);
}

// This below code will call the Hello World
void printhelloworld()
{
   pid_t child_pid = -1 ; //Global
   child_pid = fork();
   if(child_pid==0)
   {
printf("Hello from! ");
   }
   kill(child_pid, SIGKILL);
}

// Main function will use switch case

int main()
{
string msg = "Please select from the following menu: ";
string menu = " 1. Hello World "
" 2. List Files "
" 3. Exit ";
cout << msg << endl << menu;
int op;
cin >> op;
do {
   switch( op )
   {
       case 1:
           printhelloworld();
           break;
       case 2:
printls();
           break;
       case 3:
           exit(0);      
       default: cout << "Selection is not Done Re Select from Menu" << endl; break;
   }
}while (op >3);

return 0;
}