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 and Used on Linux. Description: Write a program that

ID: 3693382 • Letter: P

Question

Program to be written in C and Used on Linux.

Description: Write a program that will accept a number of arguments from the command-line – maximum of 7 – each a unique integer between 0-9. The program (parent process) will request shared memory for these integers, attach the shared memory to its own address space and fill the space (using an array) with the integers from the command-line. The parent will display the current state of the shared memory and then spawn a number of children equal to the number of arguments, and wait for each child to complete its tasks. Upon completion of all children, the parent will acknowledge said completion (and exit codes), display the current state of the shared memory, detach the shared memory, remove the shared memory, and then exit. Each child process will receive a unique ID upon initiation – an integer between 0 and the number or arguments. Child processes display the shared memory and private memory (unique ID) upon initiation. Each child will display the current state of the shared memory and their unique ID. Next each child will locate the array element (index) associated with their unique ID and then multiply that array element by their unique ID, storing the result in the array element. Each child will then display the current state of the shared memory and exit. Input: Command-line will be validated, as normal.

Output: Each step (function?) that the program (parent or child) takes (starting, validating, requesting/removing shared memory, attaching/detaching shared memory, forking/completing child processes, exiting, etc.) will print a trace statement in order to show which statements are being executed. The parent will prefix each trace statement with ‘Parent: ’ and each child will prefix each trace statement with ‘Child ID: ’, where ID is their unique ID.

Requirements: Appropriate error handling should be included for the spawning of processes and for each step of the shared memory process. Use of MakeFile will be required for this assignment.

Explanation / Answer


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

int main (int argc,char *argv[])
{
   int fd,uniqint,i,array[7],shmid,*shmptr,status
   char buf[100];
   caddr_t result;
   pid_t ParentId,Child_id;
   key_t key;
   fork();
if(argc > 1 ||argc< 8)
   {
   printf("Enter unique integer between 0-9");
   scanf("%i" ,&uniqint);
   }
for(int j=0;j<argc;j++)
{scanf("%ld",array[j]);
}
shmid=shmget(key,4*sizeof(int),IPC_CREATE|0666);
shmptr=(int *)shmat(shmid,NULL,0);
   Parentid= getpid();
   childid=getpid();
if((pid=fork())==0)
{
Child(shmptr);
exit(0);

}
wait(&status);
shmdt((void *)shmptr);
shmctl(shmid,IPC_RMID,NULL);
}

}