Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <unistd.h>
- #include <sys/types.h>
- #include <sys/wait.h>
- #include <sys/stat.h>
- #include <fcntl.h>
- #include <string.h>
- /*
- * main method
- *
- * @args
- */
- main(int argc, char* argv[])
- {
- int fd[2], pid, i;
- char pipeBuffer[1024];
- //print error and exit program if no arguments were specified
- if(argc != 2)
- {
- printf("Usage: my_program <filname of textfile>\n");
- exit(0);
- }
- //create a pipe
- if(pipe(fd) == -1)
- {
- perror("pipe");
- exit(EXIT_FAILURE);
- }
- //create a fork
- if((pid = fork()) == -1) //if fork failed
- {
- perror("fork");
- exit(EXIT_FAILURE);
- }
- if(pid == 0) //child created
- {
- close(fd[1]); //close unused write end
- int letterCounter = 0;
- int counter = 0;
- printf("\n");
- //read letters from the pipe
- while(read(fd[0], pipeBuffer, 1) > 0)
- {
- if(isalpha(pipeBuffer[counter]))
- {
- letterCounter++;
- printf("%c", pipeBuffer[counter]);
- }
- counter++;
- }
- printf("\n\nChild counting letters: %d\n\n", letterCounter);
- close(fd[0]); //close finished read end
- _exit(EXIT_SUCCESS);
- }
- else //parent
- {
- close(fd[0]); //close unused read end
- //store file contents in a buffer
- char fileBuffer[1024];
- FILE *fp = fopen(argv[1], "r");
- int c;
- int count = 0;
- while((c = fgetc(fp)) != EOF)
- {
- fileBuffer[count] = c;
- printf("%d %c\n", count, fileBuffer[count]);
- count++;
- }
- fclose(fp);
- printf("write return: %d\n", write(fd[1], fileBuffer, count)); //write to the pipe
- write(fd[1], fileBuffer, count);
- close(fd[1]); //close finished write end
- wait(NULL); //prevent zombies
- exit(EXIT_SUCCESS);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement