Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /// Unix, лабораторная работа №3, вариант №6
- /// 2012/05/03 0:32
- /// Компиляция:
- /// * Запустить два терминала
- /// * gcc server.c -o server.out
- /// * gcc client.c -o client.out
- /// * В первом терминале запустить "./server.out"
- /// * Во втором терминале запустить "./client.out"
- /// * После работы программы может понадобится удалить файл "fifo", появляющийся в рабочей папке программы.
- /// Файлы:
- /// server.c:
- #include <unistd.h>
- #include <stdio.h>
- #include <fcntl.h>
- int fdata, fout;
- char nextch[1];
- int main() {
- printf("Server up.\n");
- if (mkfifo("fifo", 0666, 0) < 0) {
- perror("Error in server/mkfifo"); return 1;
- }
- //
- fout = open("fifo", O_WRONLY);
- if (fout < 0) {
- perror("Error in server/open/fifo"); return 2;
- }
- //
- fdata = open("data.txt", O_RDONLY);
- if (fdata < 0) {
- perror("Error in server/open/data.txt"); return 3;
- }
- //
- while (read(fdata, nextch, 1)) {
- if (nextch[0] == EOF) break;
- printf("> %c\n", nextch[0]);
- write(fout, nextch, 1);
- }
- close(fdata);
- return 0;
- }
- /// client.c:
- #include <stdio.h>
- #include <fcntl.h>
- #include <string.h>
- char nextch[2], lines[2][256];
- int filein, chnum = 0, line = 0;
- int main() {
- printf("Client up.\n");
- filein = open("fifo", O_RDONLY);
- FILE* fileout = fopen("out.txt", "w");
- if (filein < 0) {
- perror("Error in client/open/fifo"); return 1;
- }
- //
- nextch[1] = 0; // нужно для того чтобы делать strcat с символом
- while (read(filein, nextch, 1) > 0) {
- if (nextch[0] == 10) { // конец строки
- if (line & 1) { // если это конец четной строки
- fprintf(fileout, "%s\n%s\n", lines[1], lines[0]); // выводим строки
- strcpy(lines[1], ""); // сбрасываем строки
- strcpy(lines[0], "");
- }
- line++; // инкрементируем индекс
- } else { // просто символ, дописываем в соотв. строку:
- strcat(lines[line & 1], nextch);
- }
- chnum++;
- }
- if (line & 1) { // если это четная строка которая не завершилась
- fprintf(fileout, "%s\n%s", lines[1], lines[0]);
- } else if (strlen(lines[0])) { // если это нечетная не пустая строка
- fprintf(fileout, "%s", lines[0]);
- }
- // немного статистики:
- printf("Total symbols: %d.\nTotal lines: %d.\n", chnum, line);
- close(filein);
- fclose(fileout);
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement