什么是fork
,什么是pipe
?
任何解释为什么需要使用它们的场景都将不胜感激。
C中的fork
和pipe
有什么区别?
我们可以在 C++ 中使用它们吗?
我需要知道这是因为我想用 C++ 实现一个程序,该程序可以访问实时视频输入、转换其格式并将其写入文件。 最好的方法是什么? 我为此使用了x264。到目前为止,我已经实现了文件格式的转换部分。 现在我必须在直播中实现它。 使用管道是个好主意吗?在另一个进程中捕获视频并将其提供给另一个进程?
最佳答案
管道是一种用于进程间通信的机制。一个进程写入管道的数据可以被另一个进程读取。创建管道的原语是 pipe
函数。这将创建管道的读取和写入端。单个进程使用管道与自己对话并不是很有用。在典型的使用中,一个进程在它forks
一个或多个子进程之前创建一个管道。然后管道用于父进程或子进程之间或两个兄弟进程之间的通信。在所有操作系统外壳中都可以看到这种通信的一个熟悉示例。当您在 shell 中键入命令时,它将通过调用 fork
生成由该命令表示的可执行文件。一个管道打开到新的子进程,它的输出被 shell 读取和打印。 This page有 fork
和 pipe
函数的完整示例。为方便起见,代码转载如下:
#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;
}
}
就像其他 C 函数一样,您可以在 C++ 中同时使用 fork
和 pipe
。
关于c++ - c中的fork()和管道(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4812891/