tubería famosa de Linux

1. Los conceptos básicos de las tuberías con nombre

Las canalizaciones con nombre también se denominan archivos FIFO, son visibles en el sistema de archivos y se pueden leer y escribir como otros archivos.

Características de las tuberías con nombre:

  1. Cuando el proceso de escritura escribe datos en la canalización, si no hay un proceso para leer los datos, el proceso de escritura se bloqueará
  2. Al leer datos en la tubería, si no hay datos, el proceso de lectura se bloqueará
  3. Cuando el proceso de escritura está bloqueado, hay un proceso de lectura para leer los datos, luego el proceso de escritura vuelve a la normalidad
  4. Cuando el proceso de lectura está bloqueado, si el proceso de escritura escribe datos, el proceso de lectura leerá los datos y luego ejecutará el siguiente código normalmente

2. concha

2.1 Crear una canalización:

$ mkfifo /tmp/testpipe

2.2 Comunicación entre líneas de comando

cat < /tmp/testpipe &
echo "hegaozhi" > /tmp/testpipe

2.3 leer

#########################################################################
# File Name: reader.sh
# Author: hegaozhi
# mail: [email protected]
# Created Time: 2020年01月03日 星期五 11时05分19秒
#########################################################################
#!/bin/bash
# filename: reader.sh
# 逐行读取管道中的内容
pipe=/tmp/testpipe
trap "rm -f $pipe" EXIT
if [[ ! -p $pipe ]]; then
    mkfifo $pipe
fi
while true
do
    if read line <$pipe; then
        if [[ "$line" == 'quit' ]]; then
            break
        else
            echo $line
        fi
    fi
done
echo "Stop reader...."

2.4 escribir

#########################################################################
# File Name: writer.sh
# Author: hegaozhi
# mail: [email protected]
# Created Time: 2020年01月03日 星期五 11时07分18秒
#########################################################################
#!/bin/bash
# writer.sh
# 把当前进程的pid写到管道
pipe=/tmp/testpipe
if [[ ! -p $pipe ]]; then
    echo "Reader not running"
    exit 1
fi

while true
do
    if [[ "$1" ]]; then
        echo "$1" >$pipe
    else
        echo "Hello from $$" >$pipe
    fi
    sleep 1
done

3. Lenguaje C

3.1 lector.c

/*************************************************************************
    > File Name: reader.c
    > Author: hegaozhi
    > Mail: [email protected] 
    > Created Time: 2020年01月03日 星期五 11时25分07秒
 ************************************************************************/

#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <string.h>
#include <fcntl.h>
#include <sys/select.h>
#include <sys/stat.h>
#include <errno.h>
#include <unistd.h>

#define FIFO "/tmp/testpipe"
int main()
{
	int rfd;
	char str[32];
	int i ;
	printf("读程序\n");
	
	if(access(FIFO,F_OK))
    {
        int ret  = mkfifo(FIFO,0777);
        if(ret == -1)
        {
            printf("Create FIFO failed!\n");
            return -1;
        }
    }
    
	rfd = open( FIFO , O_RDWR);  //O_RDONLY 只读且阻塞 
	if(rfd==-1)
	{
	    printf("Open file error\n");
	    exit(1);
	}
	
	while(1)
	{
		memset(str,0,sizeof(str));
		if((i=read(rfd,str,sizeof(str)))>0)
			printf("read:%s\n",str);
	}
	close(rfd);
}

3.2 escribir

/*************************************************************************
    > File Name: writer.c
    > Author: hegaozhi
    > Mail: [email protected] 
    > Created Time: 2020年01月03日 星期五 11时25分49秒
 ************************************************************************/
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <string.h>
 #include <unistd.h>
 
#define FIFO "/tmp/testpipe"

int main(int argc,char *argv[])
{
    if(argc < 2)
        return 0;
    int wfd;
    char str[32];
    char *str1 = "\n";
    if(access(FIFO,F_OK))
    {
        int ret  =mkfifo(FIFO,0777);
        if(ret == -1)
        {
            printf("Create FIFO failed!\n");
            return -1;
        }
    }

    sscanf(argv[1], "%s",str);
    strcat(str,str1);
    wfd  =open(FIFO, O_WRONLY|O_TRUNC);    //可读可写,存在数据则清空; O_WRONLY 只写且阻塞
	 
    if(wfd<=0)
        return 0;
        
    write(wfd, str, sizeof(str));
	 
    close(wfd);
    exit(0);
}

 

Supongo que te gusta

Origin blog.csdn.net/hgz_gs/article/details/103820540
Recomendado
Clasificación