[SOLVED] COEN177 -Lab3

30.00 $

Programming resource
Digital learning resource
Category:
✓ Practical programming resource
✓ Suitable for guided study and reference
✓ Tutor guidance available when needed

Description

5/5 - (1 vote)

Inter-process Communication – Pipes

C Program with pipe IPC

Demonstrate each of the following steps  to get a grade on this part of the lab assignment

  • Compile and run the following program

/*Sample C program for Lab assignment 3*/

#include <stdio.h>

#include <unistd.h>

#include <stdlib.h>

#include <sys/wait.h>

//main

int main() {

int fds[2];

pipe(fds);

/*child 1 duplicates downstream into stdin */

if (fork() == 0) {

dup2(fds[0], 0);

close(fds[1]);

execlp(“sort”, “sort”, 0);

}

/*child 2 duplicates upstream into stdout */

else if (fork() == 0) {

dup2(fds[1], 1);

close(fds[0]);

execlp(“ls”, “ls”, 0);

}

else {  /*parent closes both ends and wait for children*/

close(fds[0]);

close(fds[1]);

wait(0);

wait(0);

}

return 0;

}

 

  • Compile and run the following program

/*Sample C program for Lab assignment 3*/

#include <stdio.h>

#include <unistd.h>

#include <stdlib.h>

#include <string.h>

#include <sys/wait.h>

// main

int main(int argc,char *argv[]){

int  fds[2];

char buff[60];

int count;

int i;

pipe(fds);

if (fork()==0){

printf(“\nWriter on the upstream end of the pipe -> %d arguments \n”,argc);

close(fds[0]);

for(i=0;i<argc;i++){

write(fds[1],argv[i],strlen(argv[i]));

}

exit(0);

}

else if(fork()==0){

printf(“\nReader on the downstream end of the pipe \n”);

close(fds[1]);

while((count=read(fds[0],buff,60))>0){

for(i=0;i<count;i++){

write(1,buff+i,1);

write(1,” “,1);

}

printf(“\n”);

}

exit(0);

}

else{

close(fds[0]);

close(fds[1]);

wait(0);

wait(0);

}

return 0;

}

 

 

  • Modify the program in Step 2. so that the writer process passes the output of “ls” command to the upstream end of the pipe. You may use dup2(fds[1],1); for redirection and execlp(“ls”, “ls”, 0); to run the “ls” command.

 

  • Write a C program that implements the shell command: cat /etc/passwd | grep root

 

 

Producer – consumer with pipes

  • In Computer Science, the producer–consumer problem is a classic multi- process synchronization example. The producer and the consumer share a common fixed-size buffer. The producer puts messages to the buffer while the consumer removes messages from the buffer. Pipes provide a perfect solution to this problem because of their built-in synchronization capability. So as a programmer, you do not have to worry about whether or not the buffer is empty or full to produce or consume messages.

 

Write a C program to implement the producer-consumer message communication using pipes.

 

 

 

Resource details

Understand the Task Before You Use the Resource

Review the requirements, identify the programming concepts involved, study the implementation and test your understanding with your own examples and modifications.