Untitled
unknown
plain_text
a month ago
2.7 kB
1
Indexable
Never
1 #include <stdio.h> 2 #include <stdlib.h> 3 #include <string.h> 4 #include <unistd.h> 5 #include <sys/types.h> 6 #include <sys/stat.h> 7 #include <fcntl.h> 8 9 #define FIFO1 "fifo1" 10 #define FIFO2 "fifo2" 11 #define MAX_BUF 1024 12 13 int main() { 14 char sentence[MAX_BUF]; 15 16 // Create two FIFOs (named pipes) 17 mkfifo(FIFO1, 0666); 18 mkfifo(FIFO2, 0666); 19 20 int fd1, fd2; 21 22 if (fork()) { 23 // Parent Process (Process1) 24 fd1 = open(FIFO1, O_WRONLY); 25 fd2 = open(FIFO2, O_RDONLY); 26 27 while (1) { 28 printf("Enter a sentence: "); 29 fgets(sentence, MAX_BUF, stdin); 30 31 // Write the sentence to the first pipe (FIFO1) 32 write(fd1, sentence, strlen(sentence) + 1); 33 34 // Read the result from the second pipe (FIFO2) 35 read(fd2, sentence, MAX_BUF); 36 printf("Received from Process2: %s", sentence); 37 } 38 39 // Close and unlink the FIFOs 40 close(fd1); 41 close(fd2); 42 unlink(FIFO1); 43 unlink(FIFO2); 44 } else { 45 // Child Process (Process2) 46 fd1 = open(FIFO1, O_RDONLY); 47 fd2 = open(FIFO2, O_WRONLY); 48 49 while (1) { 50 // Read the sentence from the first pipe (FIFO1) 51 read(fd1, sentence, MAX_BUF); 52 53 // Process the sentence (count characters, words, and lines) 54 int char_count = 0, word_count = 0, line_count = 0; 55 char* ptr = sentence; 56 57 while (*ptr) { 58 if (*ptr != ' ' && *ptr != '\n') { 59 char_count++; 60 if (*(ptr + 1) == ' ' || *(ptr + 1) == '\n') 61 word_count++; 62 } 63 64 if (*ptr == '\n') 65 line_count++; 66 67 ptr++; 68 } 69 70 // Prepare the output 71 snprintf(sentence, MAX_BUF, "Characters: %d, Words: %d, Lines: %d\n", char_count, word_count, line_count); 72 73 // Write the result to the second pipe (FIFO2) 74 write(fd2, sentence, strlen(sentence) + 1); 75 } 76 77 // Close the pipes 78 close(fd1); 79 close(fd2); 80 } 81 82 return 0; 83 }