Linux system programming 63 processes, inter-thread communication 1-pipe

Same desk communication:

管道
XSI	:消息队列,信号量数组,共享内存

Communication between different machines

socket 网络套接字

The pipeline must make up both the read and write sides.
Provided by the kernel, simplex, self-synchronization mechanism

Anonymous pipe : piepe(), no file can be seen on the disk, which is equivalent to giving us a file descriptor or FILE* directly. The most direct result is that if there is no blood relationship between the two processes, anonymous pipes cannot be used for communication, because the other process cannot find the file location.

Named pipe : mkfifo(), the file type P as seen from the disk. Named pipes can be used to communicate between processes that are not related. Essentially, it is a file that exists on the current disk. P file

Anonymous pipeline creation

NAME
       pipe, pipe2 - create pipe

SYNOPSIS
       #include <unistd.h>

/*
pipe()返回两个文件描述符填充到 pipefd[]数组中。
pipefd[0]为读端,pipefd[1]为写端,
*/
       int pipe(int pipefd[2]);

RETURN VALUE
       On success, zero is returned.  On error, -1 is returned, and errno is set appropriately.

Named pipe creation

NAME
       mkfifo, mkfifoat - make a FIFO special file (a named pipe)

SYNOPSIS
       #include <sys/types.h>
       #include <sys/stat.h>
/*
指定我们所创建的命名管道的名字
指定操作权限
*/
       int mkfifo(const char *pathname, mode_t mode);

RETURN VALUE
       On success mkfifo() and mkfifoat() return 0.  In the case of an error, -1 is returned (in which case, errno is set appropriately). 

Insert picture description here

Experiment 1: Anonymous pipe: parent-child process parent writes and child reads, anonymous pipe

#include <stdlib.h>
#include <unistd.h>
#include <stdio.h>
#include <sys/types.h>
#include <sys/wait.h>

#define BUFSIZE 1024

int main()
{
	int pd[2];
	pid_t pid;
	char buf[BUFSIZE];
	int len;

	if(pipe(pd) < 0)//先创建匿名管道
	{
		perror("poipe()");
		exit(1);
	}


	pid = fork();//再创建子进程
	if(pid < 0)
	{
		perror("fork()");
		exit(1);
	}
	if(pid == 0) // Child read
	{
		close(pd[1]); //关闭写段
		len = read(pd[0],buf,BUFSIZE); //读取读段
		write(1,buf,len);//将读取的内容输出到终端
		close(pd[0]);//关闭读端
		exit(0);
	}
	else //Parent write
	{
		write(pd[1],"Hello!",6);//向写段写
		close(pd[0]); //关闭读端
		close(pd[1]);//关闭写端
		wait(NULL);//等收尸
		exit(0);
	}
	exit(0);
}

Guess you like

Origin blog.csdn.net/LinuxArmbiggod/article/details/114849260