Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <fcntl.h> /** fcntl */
- #include <stdio.h> /** printf */
- #include <unistd.h> /** pipe */
- #include <assert.h> /** assert */
- #include <sys/wait.h> /** wait */
- #define PID_CHILD 0
- // ls -al | wc -l && cat a.txt b.txt > c.txt.
- int console; // FD консоли
- int input; // FD первого файла, выполняющего роль STDIN_FILENO
- int output; // FD второго файла, выполняющего роль STDOUT_FILENO
- void printFile(int fd) {
- lseek(fd, 0, SEEK_SET);
- char c;
- while (read(fd, &c, sizeof(char)) > 0) {
- write(console, &c, sizeof(char));
- }
- write(console, "\n", sizeof("\n"));
- }
- void moveData(int from, int to) {
- ftruncate(to, 0);
- lseek(from, 0, SEEK_SET);
- char c;
- while (read(from, &c, sizeof(char)) > 0) {
- write(to, &c, sizeof(char));
- }
- ftruncate(from, 0);
- lseek(to, 0, SEEK_SET);
- }
- int main() {
- console = open("/dev/tty", O_WRONLY);
- input = open("/home/alex/CLionProjects/УВР/6/input.txt", O_RDWR | O_TRUNC | O_CREAT);
- output = open("/home/alex/CLionProjects/УВР/6/output.txt", O_RDWR | O_TRUNC | O_CREAT);
- assert(console != -1 && "Error: can't open console");
- assert(input != -1 && "Error: can't open input.txt" );
- assert(output != -1 && "Error: can't open output.txt");
- //close(STDOUT_FILENO);
- //fcntl(output, F_DUPFD, STDOUT_FILENO);
- dup2(output, STDOUT_FILENO);
- //close(STDIN_FILENO);
- //fcntl(input, F_DUPFD, STDIN_FILENO);
- dup2(input, STDIN_FILENO);
- /**
- * ls -al
- * Пишет в: output
- */
- int pid = fork();
- assert(pid != -1 && "Can't create new process");
- if (pid == PID_CHILD) {
- write(console, "Run command: ls /home -al\n", 26);
- execl("/bin/ls", "ls", "/home", "-al", NULL);
- }
- int status = 0;
- while ((wait(&status)) > 0) {};
- printFile(output);
- moveData(output, input);
- dup2(output, STDOUT_FILENO);
- dup2(input, STDIN_FILENO);
- /**
- * wc -l
- * Читает из input
- * Пишет в output
- */
- pid = fork();
- assert(pid != -1 && "Can't create new process");
- if (pid == PID_CHILD) {
- write(console, "Run command: wc -l\n", 19);
- execl("/usr/bin/wc", "wc", "-l", NULL);
- }
- while ((wait(&status)) > 0) {};
- printFile(output);
- /**
- * cat a.txt
- * Читает из input
- * Пишет в output
- */
- pid = fork();
- assert(pid != -1 && "Can't create new process");
- if (pid == PID_CHILD) {
- write(console, "Run command: cat a.txt b.txt\n", 23);
- execl("/bin/cat", "cat", "/home/alex/CLionProjects/УВР/6/a.txt", "/home/alex/CLionProjects/УВР/6/b.txt", NULL);
- }
- while ((wait(&status)) > 0) {};
- printFile(output);
- int c = open("/home/alex/CLionProjects/УВР/6/c.txt", O_RDWR | O_TRUNC);
- moveData(output, c);
- return 0;
- }
Advertisement