Register Now

Login

Lost Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Login

Register Now

Welcome to All Test Answers

bash program called producer and a C program called consumer.c

Assignment 3
Write a bash program called producer and a C program called consumer.c. A text-based data file
called storage initially contains an integer number between 5 and 90.
The producer checks the number in the storage. If the current number plus 8 will be 100 or
larger, it will terminate. Otherwise, it will increase the number in the storage by 8 and then call
the consumer to continue.
The consumer decreases the number in the storage by 3, and then calls the producer to continue.
Both the producer and the consumer can be the starter.
The C program must use system call I/O. No standard I/O library functions are allowed. It must
fork a separate process to call the producer to continue.
Sample runs:

bash program called producer and a C program called consumer.c.

bash program called producer and a C program called consumer.c.

Answer:

consumer.c

/*
Description:	Subtract 3 from the integer stored in storage,
				write new number into storage
				execute bash file "producer.sh"	

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>
#include <string.h>

int main(){
	FILE *fd;
        fd = fopen("storage","rw+" );   // Open file allowing read and write 
      	char buf[2];
	int sub, pid;
	fscanf(fd, "%s",buf);    // reads storage, and store value into buf
	int num = atoi(buf);	// convert to int
	sub = num - 3;      // take value in buf and subtract by 3
	printf("from consumer: current total is %d\n",sub);
	fseek(fd, 0, SEEK_SET);	// set file pointer to beginning
        fprintf(fd,"%d",sub);   // write new value into storage
	pid = fork();
	if(pid == 0){
        	execlp("./producer.sh", "producer", NULL);   // execute producer.sh
	}
	fclose(fd);
	return 0;
}

producer

#!/bin/bash
#Description:	Add 8 from integer that is stored in storage					 			
#				write new number into storage, 	   						   			
#				execute C program "consumer.c"	     	 

val=$(< storage)   #store value in storage into val
max=100
	# if val is less then max
	if [ $val -lt $max ]
	then
		let num=$val+8   # calculate value + 8
		
		# check to see if $val + 8 > 100
		if [ $num -ge $max ]
		then
			echo "from producer: Now I will take the rest!" 
			exit  # exit the whole program if over 100
		fi
		
		echo "from producer: current total is $num"	
		echo $num > storage    # overwrite storage with new value 
		./consumer      # execute consumer.c
	
	# if over value in storage is > 100 end program
	else 
		echo "from producer: Now I will take the rest!" 
	fi


About

Leave a reply

Captcha Click on image to update the captcha .

error: Content is protected !!