パイプはプロセス間通信のメカニズムです。 1つのプロセスによってパイプに書き込まれたデータは、別のプロセスで読み取ることができます。パイプを作成するためのプリミティブはpipe
関数です。これにより、パイプの読み込みと書き込みの両方の端が作成されます。 1つのプロセスがパイプを使用して自分自身と通信することはあまり役に立ちません。典型的な使用では、プロセスは1つまたは複数の子プロセスの直前にパイプを作成します(forks
)。このパイプは、親プロセスまたは子プロセス間、または2つの兄弟プロセス間の通信に使用されます。この種の通信に関するよく知られた例は、すべてのオペレーティングシステムのシェルで見ることができます。シェルでコマンドを入力すると、そのコマンドで表される実行可能ファイルが呼び出され、fork
が呼び出されます。パイプが新しい子プロセスに開かれ、その出力がシェルによって読み込まれ、出力されます。 This pageには、fork
とpipe
関数の完全な例があります。ちょうどあなたがC++でfork
とpipe
の両方を使用することができ、他のC関数のように
#include <sys/types.h>
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
/* Read characters from the pipe and echo them to stdout. */
void
read_from_pipe (int file)
{
FILE *stream;
int c;
stream = fdopen (file, "r");
while ((c = fgetc (stream)) != EOF)
putchar (c);
fclose (stream);
}
/* Write some random text to the pipe. */
void
write_to_pipe (int file)
{
FILE *stream;
stream = fdopen (file, "w");
fprintf (stream, "hello, world!\n");
fprintf (stream, "goodbye, world!\n");
fclose (stream);
}
int
main (void)
{
pid_t pid;
int mypipe[2];
/* Create the pipe. */
if (pipe (mypipe))
{
fprintf (stderr, "Pipe failed.\n");
return EXIT_FAILURE;
}
/* Create the child process. */
pid = fork();
if (pid == (pid_t) 0)
{
/* This is the child process.
Close other end first. */
close (mypipe[1]);
read_from_pipe (mypipe[0]);
return EXIT_SUCCESS;
}
else if (pid < (pid_t) 0)
{
/* The fork failed. */
fprintf (stderr, "Fork failed.\n");
return EXIT_FAILURE;
}
else
{
/* This is the parent process.
Close other end first. */
close (mypipe[0]);
write_to_pipe (mypipe[1]);
return EXIT_SUCCESS;
}
}
:あなたの便宜のために、コードを以下に再現されます。
誰かがVC++で "unistd.h"の代替案を教えてもらえますか – nightWatcher
http://blogs.msdn.com/b/bclteam/archive/2006/12/07/introducing-pipes-justin-van- patten.aspx for answer – nightWatcher