Question

In: Computer Science

Use fork() Create a program that reads characters from an input file. Use fork to create...

Use fork()

Create a program that reads characters from an input file. Use fork to create parent and child processes.

The parent process reads the input file. The input file only has letters, numbers. The parent process calculates and prints the frequency of the symbols in the message, creates the child processes, then prints the information once the child processes complete their execution.

The child processes receives the information from the parent, generates the code of the assigned symbol by the parent, and saves the generated code into a file.

Example:

Input.txt: aaaannnaaakkllaaaaap

Output.txt:

a frequency = 12

n frequency = 3

k frequency = 2

l frequency = 2

p frequency = 1

Original Message: aaaannnaaakkllaaaaap

Solutions

Expert Solution

Remember: fork() is not available on windows machine, you can use cygwin if want to execute on windows.

Here it the code:

main.c (CODE)

code text

#include <stdio.h>

#include <sys/types.h>

#include <stdlib.h>

#include <unistd.h>

#include<sys/wait.h>

//For mapping character and its count.

struct icmap{

char c;

int count;

};

int main(void) {

//File handler for output and input.

FILE *input, *output;

//For reading file character by character.

char ch;

//Storing file text while reading char by char.

char originalMessage[100];

//Creating a map of size 1.

//When reading file, dynamically increase the size of map.

struct icmap* map = malloc(sizeof(struct icmap));

//Overall map array length.

int length = 1;

//For loop count

int i,j;

//Flag for check read letter is already in map or not.

int addNewLetter = 0;

//Child process id, to know which process is of child.

pid_t childProcessId;

//Openning input file for reading char by char.

input = fopen("input.txt", "r");

//Read first char and store it in map.

ch = fgetc(input);

map[0].c = ch;

map[0].count = 0;

j = 0;

//Loop through file text until end of file.

while(ch != EOF){

//Store the file text.

originalMessage[j++] = ch;

addNewLetter = 1;

//Check for char already exist or not.

//If already exist increase its count by 1.

//And mark the the flag, not to add this letter.

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

if(map[i].c == ch){

map[i].count = map[i].count + 1;

addNewLetter = 0;

break;

}

}

//If letter is new then increase the size of map, and add it.

if(addNewLetter == 1){

length++;

map = realloc(map, sizeof(struct icmap) * length);

map[length-1].count = 1;

map[length-1].c = ch;

}

ch = fgetc(input);

}

//Close the input file.

fclose(input);

printf("Frequency calculation completed. Now creating child process.\n");

//Create child process.

childProcessId = fork();

if(childProcessId == 0){

//Processing from child process.

//Open the file and save all information.

output = fopen("output.txt", "w");

for(int i=0;i<length;i++){

fprintf(output, "%c frequency = %d\n",map[i].c, map[i].count);

originalMessage[i] = map[i].c;

}

//save the original message.

fprintf(output, "Original Message: %s",originalMessage);

//Close the file.

fclose(output);

printf("Child process complete.\n");

//Exit the child process, so main process continue its execution.

exit(0);

}else{

//Parent process. wait for child process to complete.

wait(NULL);

}

printf("Output file saved successfully.");

return 0;

}

Output

Output File

Code without using any struct

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

const int MAX_CHAR = 100;

int main(void) {

//File handler for output and input.
FILE *input, *output;

//For reading file character by character.

char ch;

//Storing file text while reading char by char.

char originalMessage[MAX_CHAR];

//storing freq with letter respectively

char chars[MAX_CHAR];

int freqs[MAX_CHAR];

//Overall array length.

int length = 0;

//For loop count

int i,j;

//Flag for check read letter is already in map or not.

int addNewLetter = 0;

//Child process id, to know which process is of child.

pid_t childProcessId;

//Openning input file for reading char by char.

input = fopen("input.txt", "r");

//Read first char and store it in map.

ch = fgetc(input);

j = 0;

//Loop through file text until end of file.

while(ch != EOF){

//Store the file text.

originalMessage[j++] = ch;

addNewLetter = 1;

//Check for char already exist or not.

//If already exist increase corresponding frequency count by 1.

//And mark the the flag, not to add this letter.

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

if(chars[i] == ch){

freqs[i] = freqs[i] + 1;

addNewLetter = 0;

break;

}

}

//If letter is new then add letter to array and increase the frequency and length value..

if(addNewLetter == 1){

length++;

freqs[length-1] = 1;

chars[length-1] = ch;

}

ch = fgetc(input);

}


//Close the input file.

fclose(input);

printf("Frequency calculation completed. Now creating child process.\n");

//Create child process.

childProcessId = fork();

if(childProcessId == 0){

//Processing from child process.

//Open the file and save all information.

output = fopen("output.txt", "w");

for(int i=0;i<length;i++){

fprintf(output, "%c frequency = %d\n",chars[i], freqs[i]);

}

//save the original message.

fprintf(output, "Original Message: %s",originalMessage);

//Close the file.

fclose(output);

printf("Child process complete.\n");

//Exit the child process, so main process continue its execution.

exit(0);

}else{

//Parent process. wait for child process to complete.

wait(NULL);

}

printf("Output file saved successfully.");

return 0;

}


Related Solutions

Write a program that reads in characters until end of file. The program should count and...
Write a program that reads in characters until end of file. The program should count and print the number of characters, printable characters, vowels, digits, and consonants in the input. Use functions to check whether a character is a vowel, a consonant, or a printable character. Define and use macros to test if a character is a digit or a letter.
Part 1 Write a program that reads a line of input and display the characters between...
Part 1 Write a program that reads a line of input and display the characters between the first two '*' characters. If no two '*' occur, the program should display a message about not finding two * characters. For example, if the user enters: 1abc*D2Efg_#!*345Higkl*mn+op*qr the program should display the following: D2Efg_#! 1) Name your program stars.c. 2) Assume input is no more than 1000 characters. 3) String library functions are NOT allowed in this program. 4) To read a...
ASSIGNMENT: Write a program and use the attached file (babynames.txt) as input file, and create two...
ASSIGNMENT: Write a program and use the attached file (babynames.txt) as input file, and create two output tiles. One file listing out all boys names, and the other file listing out all girls name. CODE: (teacher gave some of the code below use it to find the answer please String B is the boy names String E is girl names) import java.io.File; import java.io.FileNotFoundException; import java.io.PrintWriter; import java.util.Scanner; /** This program reads a file with numbers, and writes the numbers...
ASSIGNMENT: Write a program and use the attached file (babynames.txt) as input file, and create two...
ASSIGNMENT: Write a program and use the attached file (babynames.txt) as input file, and create two output tiles. One file listing out all boys names, and the other file listing out all girls name. CODE: (teacher gave some of the code below use it to find the answer please String B is the boy names String E is girl names) import java.io.File; import java.io.FileNotFoundException; import java.io.PrintWriter; import java.util.Scanner; /** This program reads a file with numbers, and writes the numbers...
Write a program that reads two strings from an input file (The first line is X,...
Write a program that reads two strings from an input file (The first line is X, the second line is Y), compute the longest common subsequence length AND the resulting string. You will need to write 2 methods 1) return LCS length in iterative function // return the length of LCS. L is the 2D matrix, X, Y are the input strings, m=|X|, n=|Y| int lcs_it(int **C, string X, string Y, int m, int n ) 2) return LCS resulting...
I am trying to create a program that reads from a csv file and finds the...
I am trying to create a program that reads from a csv file and finds the sum of total volume in liters of liquor sold from the csv file by county and print that list out by county in descending order. Currently my program runs and gives me the right answers but it is not in descending order. I tried this:     for county, volume in sorted(sums_by_volume.items(), key=lambda x: x[1], reverse=True):         index +=1         print("{}. {} {:.2f}".format(county, sums_by_volume[county]))      When I run...
Java: create a program that reads in a piece of DNA sequence from a sequence file...
Java: create a program that reads in a piece of DNA sequence from a sequence file (dna.seq) (alternatively you can use the getRandomSeq(long) method of the RandomSeq class to generate a piece of DNA sequence), and then print out all the codons in three forward reading frames. Design a method called codon() that can be used to find all the codons from three reading frames. The method will take in an argument, the reading frame (1, 2, or 3), and...
2. Write a Java program that reads a series of input lines from given file “name.txt”,...
2. Write a Java program that reads a series of input lines from given file “name.txt”, and sorts them into alphabetical order, ignoring the case of words. The program should use the merge sort algorithm so that it efficiently sorts a large file. Contents of names.text Slater, KendallLavery, RyanChandler, Arabella "Babe"Chandler, StuartKane, EricaChandler, Adam JrSlater, ZachMontgomery, JacksonChandler, KrystalMartin, JamesMontgomery, BiancaCortlandt, PalmerDevane, AidanMadden, JoshHayward, DavidLavery,k JonathanSmythe, GreenleeCortlandt, OpalMcDermott, AnnieHenry, DiGrey, MariaEnglish, BrookeKeefer, JuliaMartin, JosephMontgomery, LilyDillon, AmandaColby, LizaStone, Mary FrancesChandler, ColbyFrye, DerekMontgomery,...
Write a C program that reads a file and reports how many lines, words, and characters...
Write a C program that reads a file and reports how many lines, words, and characters appear in it. For the purpose of this program, a word consists of a consecutive sequence of any characters except white space characters. For example, if the file lear.txt contains the following passage from King Lear, Poor naked wretches, wheresoe’er you are, That bide the pelting of this pitiless storm, How shall your houseless haeds and unfed sides, Your loop’d and window’d raggedness, defend...
Write a program FileCounter.java that reads a text file text1.txt and reports the number of characters...
Write a program FileCounter.java that reads a text file text1.txt and reports the number of characters and lines contained in the file. For example, the output should be as follows: Lines: 5 Chars: 124 Note: Write a main() method to test in the FileCounter.java. The file path should use relative path. Must use the provided text file text1.txt. The text file say This is an example 1 This is an example 1 2. This is an example 1 2 3....
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT