- Piping in Unix or Linux
- Что такое каналы (pipe) в Linux? Как работает перенаправление каналов?
- Каналы в Linux: общая идея
- Имейте в виду: Pipe перенаправляет стандартный вывод на стандартный ввод, но не как аргумент команды
- Типы каналов в Linux
- Каналы без названия
- Именованные каналы
- Именованные каналы не занимают память на диске
- Сниженный ввод-вывод
- Связь между двумя очень разными процессами
- Понимание каналов более низкого уровня [для опытных пользователей и разработчиков]
- Working with pipes on the Linux command line
- Checking on NICs
- Examining permissions
- Counting files
- Identifying processes
- Sorting results
- Wrapping up
Piping in Unix or Linux
A pipe is a form of redirection (transfer of standard output to some other destination) that is used in Linux and other Unix-like operating systems to send the output of one command/program/process to another command/program/process for further processing. The Unix/Linux systems allow stdout of a command to be connected to stdin of another command. You can make it do so by using the pipe character ‘|’.
Pipe is used to combine two or more commands, and in this, the output of one command acts as input to another command, and this command’s output may act as input to the next command and so on. It can also be visualized as a temporary connection between two or more commands/ programs/ processes. The command line programs that do the further processing are referred to as filters.
This direct connection between commands/ programs/ processes allows them to operate simultaneously and permits data to be transferred between them continuously rather than having to pass it through temporary text files or through the display screen.
Pipes are unidirectional i.e data flows from left to right through the pipeline.
Syntax :
Example :
1. Listing all files and directories and give it as input to more command.
Output :
The more command takes the output of $ ls -l as its input. The net effect of this command is that the output of ls -l is displayed one screen at a time. The pipe acts as a container which takes the output of ls -l and gives it to more as input. This command does not use a disk to connect standard output of ls -l to the standard input of more because pipe is implemented in the main memory.
In terms of I/O redirection operators, the above command is equivalent to the following command sequence.
Output :
Output of the above two commands is same.
2. Use sort and uniq command to sort a file and print unique values.
This will sort the given file and print the unique values only.
Output :
3. Use head and tail to print lines in a particular range in a file.
This command select first 7 lines through (head -7) command and that will be input to (tail -5) command which will finally print last 5 lines from that 7 lines.
Output :
4. Use ls and find to list and print all lines matching a particular pattern in matching files.
This command select files with .txt extension in the given directory and search for pattern like “program” in the above example and print those ine which have program in them.
Output :
5. Use cat, grep, tee and wc command to read the particular entry from user and store in a file and print line count.
This command select Rajat Dua and store them in file2.txt and print total number of lines matching Rajat Dua
Output :
Источник
Что такое каналы (pipe) в Linux? Как работает перенаправление каналов?
Главное меню » Linux » Что такое каналы (pipe) в Linux? Как работает перенаправление каналов?
Вы, вероятно, также знаете, что такое перенаправление канала, которое используется для перенаправления вывода одной команды в качестве ввода для следующей команды.
Но знаете ли вы, что под ним? Как на самом деле работает перенаправление каналов?
Не беспокойтесь, потому что сегодня мы демистифицируем каналы Unix, чтобы в следующий раз, когда вы пойдете на свидание с этими причудливыми вертикальными полосами, вы точно знали, что происходит.
Примечание. Мы использовали термин Unix в некоторых местах, потому что концепция каналов (как и многие другие вещи в Linux) происходит от Unix.
Каналы в Linux: общая идея
Вот что вы повсюду увидите относительно «что такое каналы в Unix?»:
- Каналы Unix – это механизм IPC (межпроцессное взаимодействие), который перенаправляет вывод одной программы на вход другой программы.
Это общее объяснение, которое дают все. Мы хотим проникнуть глубже. Давайте перефразируем предыдущую строку более техническим языком, убрав абстракции:
- Каналы Unix – это механизм IPC (межпроцессного взаимодействия), который принимает программу stdout и пересылает ее другой программе stdin через буфер.
Намного лучше. Удаление абстракции сделало его намного чище и точнее. Вы можете посмотреть на следующую схему, чтобы понять, как работает pipe.
Один из простейших примеров команды pipe – передать некоторый вывод команды команде grep для поиска определенной строки.
Имейте в виду: Pipe перенаправляет стандартный вывод на стандартный ввод, но не как аргумент команды
Очень важно понять, что конвейер передает команду stdout другой команде stdin, но не как аргумент команды. Мы объясним это на примере.
Если вы используете команду cat без аргументов, по умолчанию будет выполняться чтение из stdin. Вот пример:
Здесь мы использовали cat без передачи файлов, поэтому по умолчанию stdin. Затем мы написали строку, а затем использовал Ctrl + d, чтобы сообщить, что закончили писать (Ctrl + d подразумевает EOF или конец файла). Как только мы закончили писать, cat прочитал stdin и написал эту строку в stdout.
Теперь рассмотрим следующую команду:
Вторая команда НЕ эквивалентна cat hey. Здесь stdout”hey” переносится в буфер и передает stdin в cat. Поскольку аргументов командной строки не было, cat по умолчанию выбрал stdin для чтения, а что-то уже было в stdin, поэтому команда cat приняла это и напечатала stdout.
Фактически, мы создали файл с именем hey и поместили в него некоторый контент.
Типы каналов в Linux
В Linux есть два типа каналов:
- Безымянный канал, также называемый анонимным.
- Именованные каналы
Каналы без названия
Без названия каналы, как следует из названия, не имеют имени. Они создаются на лету вашей оболочкой Unix всякий раз, когда вы используете символ |.
Когда люди говорят о каналах в Linux, они обычно говорят об этом. Они полезны, потому что вам, как конечному пользователю, не нужно ничего отслеживать. Ваша оболочка справится со всем этим.
Именованные каналы
Этот немного отличается. Именованные каналы действительно присутствуют в файловой системе. Они существуют как обычный файл. Вы можете создать именованный файл, используя следующую команду:
Это создаст файл с именем «pipe». Выполните следующую команду:
Обратите внимание на «p» в начале, это означает, что файл является каналом. Теперь воспользуемся этим каналом.
Как мы говорили ранее, конвейер пересылает вывод одной команды на вход другой. Это как курьерская служба, вы даете посылку доставить с одного адреса, а они доставляют по другому. Итак, первый шаг – предоставить пакет, то есть предоставить каналу что-то.
Вы заметите, что echo еще не вернули нам терминал. Откройте новый терминал и попробуйте прочитать из этого файла.
Обе эти команды завершили свое выполнение одновременно.
Это одно из фундаментальных различий между обычным файлом и именованным каналом. В канал ничего не записывается, пока какой-либо другой процесс не прочитает его.
Зачем использовать именованные каналы? Вот список того, почему вы хотите использовать именованные каналы
Именованные каналы не занимают память на диске
Если вы выполните a du -s pipe, вы увидите, что он не занимает места. Это потому, что именованные каналы похожи на конечные точки для чтения и записи из буфера памяти и в него. Все, что записывается в именованный канал, фактически сохраняется во временном буфере памяти, который сбрасывается, когда операция чтения выполняется из другого процесса.
Сниженный ввод-вывод
Поскольку запись в именованный канал означает сохранение данных в буфере памяти, операции с большими файлами значительно сокращают дисковый ввод-вывод.
Связь между двумя очень разными процессами
Выходные данные события можно мгновенно и очень эффективно получить из другого процесса с помощью именованных каналов. Поскольку чтение и запись происходят одновременно, время ожидания практически равно нулю.
Понимание каналов более низкого уровня [для опытных пользователей и разработчиков]
В следующем разделе речь идет о каналах на более глубоком уровне с фактическими реализациями. Этот раздел требует от вас базового понимания:
- Как работает программа на C
- Что такое системные вызовы
- Что такое процессы
- Что такое файловые дескрипторы
Мы не будем вдаваться в подробности примеров. Речь идет только о «каналах». Для большинства пользователей Linux этот раздел не нужен.
В конце мы предоставили для компиляции образец файла – Makefile. Имейте в виду, что эти программы предназначены только для иллюстративных целей, поэтому, если вы видите, что ошибки обрабатываются некорректно.
Рассмотрим следующий пример программы:
В строке 16 мы создали безымянный канал, используя функцию pipe(). Первое, что следует заметить, это то, что мы передали массив целых чисел со знаком длиной 2.
Это потому, что канал – это не что иное, как массив из двух целых чисел без знака, представляющих два файловых дескриптора. Один для письма, один для чтения. И оба они указывают на расположение буфера в памяти, которое обычно составляет 1 МБ.
Здесь мы назвали переменную fd. fd [0] – дескриптор входного файла, fd [1] – дескриптор выходного файла. В этой программе один процесс записывает строку в файловый дескриптор fd [1], а другой процесс читает из файлового дескриптора fd [0].
Именованный канал ничем не отличается. С именованным каналом вместо двух файловых дескрипторов вы получаете имя файла, которое можно открыть из любого процесса и работать с ним, как с любым другим файлом, учитывая при этом характеристики канала.
Вот пример программы, которая делает то же самое, что и предыдущая программа, но вместо анонимного канала создает именованный канал.
Здесь мы использовали системный вызов mknod для создания именованного канала. Как вы можете видеть, хотя мы удалили канал по завершении, вы вполне можете оставить его и легко использовать для связи между различными программами, просто открыв и записав в файл с именем «npipe» в моем случае.
Вам также не придется создавать два разных канала для двусторонней связи, как в случае с анонимными каналами.
Вот образец Makefile, как и было обещано. Поместите его в тот же каталог, что и предыдущие программы, с именами «pipe.c» и «fifo.c» соответственно.
Вот так. Это действительно все, что есть в каналах Unix.
Если вы нашли ошибку, пожалуйста, выделите фрагмент текста и нажмите Ctrl+Enter.
Источник
Working with pipes on the Linux command line
I’m sorry to inform you, but the command line didn’t die off with the dinosaurs, nor did it disappear with the dodo or the carrier pigeon. The Linux command line is alive and well, and still going strong. It is an efficient way of quickly gathering and processing information, creating new scripts, and configuring systems.
One of the most powerful shell operators is the pipe ( | ). The pipe takes output from one command and uses it as input for another. And, you’re not limited to a single piped command—you can stack them as many times as you like, or until you run out of output or file descriptors.
One of the main purposes of piping is filtering. You use piping to filter the contents of a large file—to find a particular string or word, for example. This purpose is why the most popular use for pipes involves the commands grep and sort . But, you’re not limited to those cases. You can pipe the output to any command that accepts stream input. Let’s look at a theoretical example as an illustration of how this process works:
Both cmd1 and cmd2 are command line utilities that output their results to the screen ( stdout ). When you pipe one command’s output to another, however, the information from cmd1 doesn’t produce output to the screen. The pipe redirects that output as input to cmd2 .
Note: Don’t confuse pipe ( | ) redirection with file redirection ( > ) and ( ). (An example of file redirection: cmd1 > file or cmd1 .) File redirection either sends output to a file instead of the screen, or pulls input from a file.
Let’s look at some real-world examples of how piping works.
Checking on NICs
Let’s say that you need to know if one of your network interface cards (NICs) has an IP address beginning with 192:
$ ifconfig | grep 192
inet 192.168.1.96 netmask 255.255.255.0 broadcast 192.168.1.255
You can also find out which live NICs you have on a system with a simple pipe to grep :
$ ifconfig | grep UP
enp0s3: flags=4163 mtu 1500
lo: flags=73 mtu 65536
You could also grep for «RUNNING» or «RUN» to display the same information.
Examining permissions
Maybe you want to find out how many directories under /etc are writeable by root:
$ sudo ls -lR | grep drwx
The results are too long to list here, but as you can see from your displayed list, there are a lot of them. You still need to find out how many there are, and a visual count would take a long time. An easy option is to pipe the results of your ls command to the wc (word count) command:
$ sudo ls -lR | grep drwx | wc -l
The -l switch displays the number of lines. Your count might be different. This listing is from a fresh «RHEL 8 server no GUI» install.
[Want to try out Red Hat Enterprise Linux? Download it now for free.]
Counting files
You don’t have to use grep all the time. For example, you can list the number of files in the /etc directory with this:
Again, your results might look different, but you know something is wrong if the command returns a small number of files.
Identifying processes
You can also perform complex tasks using pipes. To list the process IDs (PIDs) for all systemd -related processes:
$ ps -ef | grep systemd | awk ‘< print $2 >‘
The awk command’s $2 output isolates the second (PID) column from the ps command. Note that the last entry, PID 17242 , is actually the PID for the grep command displaying this information, as you can see from the full listing results here:
khess 17242 7505 0 09:40 pts/0 00:00:00 grep —color=auto systemd
To remove this entry from your results, use the pipe operator again:
$ ps -ef | grep systemd | awk ‘< print $2 >‘ | grep -v grep
The -v switch tells the grep command to invert or ignore lines that contain the string that follows—in this case any line containing the word «grep.»
Sorting results
Another popular use of the pipe operator is to sort your results by piping to the sort command. Say that you want to sort the list of names in contacts.txt . First, let’s look at the contents as they are in the file before sorting:
Bob Jones
Leslie Smith
Dana David
Susan Gee
Leonard Schmidt
Linda Gray
Terry Jones
Colin Doe
Jenny Case
Now, sort the list:
$ cat contacts.txt | sort
Bob Jones
Colin Doe
Dana David
Jenny Case
Leonard Schmidt
Leslie Smith
Linda Gray
Susan Gee
Terry Jones
You can reverse the sort order with the -r switch:
$ cat contacts.txt | sort -r
Terry Jones
Susan Gee
Linda Gray
Leslie Smith
Leonard Schmidt
Jenny Case
Dana David
Colin Doe
Bob Jones
Was the output for either of these what you expected? By default, the sort command performs a dictionary sort on the first word or column, which is why Bob Jones and Terry Jones are not listed one after the other.
You can sort by the second column with the -k switch, specifying the column you want to sort on, which in our list is column two:
$ cat contacts.txt | sort -k2
Jenny Case
Dana David
Colin Doe
Susan Gee
Linda Gray
Bob Jones
Terry Jones
Leonard Schmidt
Leslie Smith
If you have a long contact list and you think that this list contains duplicate entries, you can pipe your list to sort and then uniq to remove those duplicates:
$ cat contacts.txt | sort | uniq
This command only displays unique entries, but it doesn’t save the results. To sort the file, filter unique entries, and then save the new file, use this:
$ cat contacts.txt | sort -k2 | uniq > contact_list.txt
Remember that the pipe operator and the file redirect operators do different things.
Wrapping up
Now that you’ve had a taste of the command line’s power, do you think you can handle the responsibility? Command line utilities have more flexibility than their graphical counterparts do. And for some tasks, there are no graphical equivalents.
The best way to learn command line behavior is to experiment. For example, the sort command didn’t do what you thought it should until you explored further. Don’t forget to use the power of your manual ( man ) pages to find those «hidden» secret switches and options that turn command line frustration into command line success.
Источник