Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- #include <stdlib.h>
- #include <unistd.h>
- #include <sys/types.h>
- #include <sys/wait.h>
- int main(int argc, char **argv)
- {
- //If only one input then user has not provided a file name to calculate.
- if(argc == 1)
- {
- printf("No file provided. Please provide name of file needed to add.\n");
- }
- else{
- FILE *inputFile; //file to be calculated
- double inputNumber; //each number in the file
- double answer = 0; //final answer
- int count = 0; //counter variable to make sure there are numbers in the file
- int forkCounter = 1;
- int addUpPipe[2]; //float array for pipe
- pid_t childPid; //id of child
- pipe(addUpPipe); //create pipe
- /**
- for(int i = 1; i < argc - 1; i++){
- childPid = fork();
- if(childPid > 0){
- fopen("%s", argv[i]); //Opens provided file name and stores in variable
- }
- }
- **/
- //Fork process for however many arguments are provided
- while((childPid = fork()) > 0 && forkCounter < argc - 1){
- fopen("%s", argv[forkCounter]);
- ++forkCounter;
- printf("Forked %d\n",forkCounter);
- }
- //Parent code
- //If parent, wait for children to finish then open pipe, add answers, then send to command line
- if(childPid > 0){
- int returnStatus;
- double value;
- double finalAnswer = 0;
- printf("%s\n", "Entered Parent");
- while(wait(&returnStatus) > 0); //Wait until children are finished
- printf("%s", "Finished waiting for child");
- //Reads the added value from pipe
- FILE* readPipe = fdopen(addUpPipe[0], "r");
- while(fscanf(readPipe, "%lf", &value) != EOF){
- finalAnswer += value;
- }
- printf("%lf", value); //Print completed value to command line
- close(addUpPipe[0]); //Close pipe
- }
- //Child Code
- else{
- //If file is null it cant be opened or doesnt exist
- printf("%s\n", "Entered Child");
- if(inputFile == NULL)
- {
- printf("Cant open file or file does not exist\n");
- return 0;
- }
- //Goes through file and adds each number together while increasing the counter variable
- while(fscanf(inputFile, "%lf", &inputNumber) != EOF)
- {
- answer += inputNumber;
- count++;
- }
- //If reached the end of file immediately without count increasing, must be empty
- if(count == 0)
- {
- printf("Error! No numbers in file!\n");
- }
- //Otherwise, print the answer
- else
- {
- //printf("%d", answer);
- write(addUpPipe[1], &answer, sizeof(answer));
- write(addUpPipe[1], "\n", 2);
- close(addUpPipe[1]);
- printf("%s", "Child done");
- }
- fclose(inputFile); //Close file
- }
- return 0;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement