Linuxシステムプログラミング63プロセス、スレッド間通信1パイプ

同机通信:

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

異なるマシン間の通信

socket 网络套接字

パイプラインは、読み取り側と書き込み側の両方を構成する必要があります。
カーネル、シンプレックス、自己同期メカニズムによって提供されます

匿名パイプ:piepe()、ディスク上にファイルが表示されません。これは、ファイル記述子またはFILE *を直接指定するのと同じです。最も直接的な結果は、2つのプロセス間に血縁関係がない場合、他のプロセスがファイルの場所を見つけることができないため、無名パイプを通信に使用できないことです。

名前付きパイプ:mkfifo()、ディスクから見たファイルタイプP。名前付きパイプは、関連のないプロセス間で通信するために使用できます。基本的に、これは現在のディスクに存在するファイルです。Pファイル

匿名のパイプライン作成

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.

名前付きパイプの作成

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). 

ここに画像の説明を挿入

実験1:無名パイプ:親子プロセスの親の書き込みと子の読み取り、無名パイプ

#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);
}

おすすめ

転載: blog.csdn.net/LinuxArmbiggod/article/details/114849260