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

Linux and C pipe system call Code for Lab 5 that is mentioned: #include <stdio.h

ID: 3829421 • Letter: L

Question

Linux and C pipe system call

Code for Lab 5 that is mentioned:

#include <stdio.h>
#include <sys/ipc.h>
#include <sys/shm.h>

int main()
{
int shmid, status;
int *a, *b;
int i;

shmid = shmget(IPC_PRIVATE, sizeof(int), 0777|IPC_CREAT);
int *temp=(int *)shmat(shmid,0,0);
*temp=19530;

int start=1;
// for(i=0;i<5;i++)
// {
if (fork() == 0) {

b = (int *) shmat(shmid, 0, 0);
if(start==1)
{b[0]=19530;
start=0;
}
for( i=0; i< 5; i++) {
if(i==0)
b[0]=19530;
sleep(1);
b[0]-=5;
printf(" Child reads: %d ",b[0]);
}


shmdt(b);

}
else {

a = (int *) shmat(shmid, 0, 0);

  
for( i=0; i< 5; i++) {
sleep(1);
a[0] = a[0]/5;
printf("Parent writes: %d, ",a[0]);
}
wait(&status);

shmdt(a);

shmctl(shmid, IPC_RMID, 0);
}
}

Read the man page of pipe system call. 2 partially completed programs have been provided to help teach you pipes. For this lab you are to create an output identical to that of lab 5(x-5, x/5, etc.). This time you are using pipes though. Since pipes have a built in mechanism for process control, you only need to use 2 processes each which loop 5 times (instead of creating a new process every time you loop Wait then won't work for this lab. If you need help controlling process order, try using the system call sleep0. Following is a sample output that will be printed to the screen/terminal. 19530 ITERATION 1 Child x 19525 Parent 3905 ITERATION 2 Child x 3900 Parent 780 ITERATION 3 Child x 775 Parent 155 ITERATION 4 Child x 150 Parent x 30 ITERATION 5 Child x 25 Parent

Explanation / Answer

#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>

int main(void)
{
int fd[2], nbytes;
pid_t cpid;
char readbuffer[80];

pipe(fd);
  
if((cpid = fork()) == -1)
{
perror("fork");
exit(1);
}

if(cpid == 0)
{
  
  
for( i=0; i< 5; i++) {
if(i==0)
b[0]=19530;
sleep(1);
b[0]-=5;
printf(" Child reads: %d ",b[0]);
       close(fd[0]);
exit(0);
}
else
{
a = (int *) shmat(shmid, 0, 0);
  
for( i=0; i< 5; i++) {
sleep(1);
a[0] = a[0]/5;
printf("Parent writes: %d, ",a[0])
close(fd[1]);

  
  
}
  
return(0);
}

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote