什么是fork?什么是pipe?任何解释为什么它们的使用是必要的场景都将受到欢迎。C语言中的fork和pipe有什么不同?我们可以在C++中使用它们吗?
我需要知道这是因为我想在C++中实现一个程序,可以访问实时视频输入,转换其格式,并将其写入文件。解决这一问题的最佳方法是什么?为此,我使用了x264。到目前为止,我已经实现了文件格式的转换部分。现在我必须在实况流上实现它。使用管道是个好主意吗?在另一个进程中捕获视频并将其提供给另一个进程?
发布于 2011-01-27 13:11:43
管道是进程间通信的一种机制。一个进程写入管道的数据可以被另一个进程读取。创建管道的原语是pipe函数。这将创建管道的读写两端。单个进程使用管道与自身通信的用处不是很大。在典型的使用中,一个进程在它forks一个或多个子进程之前创建一个管道。然后,管道用于父进程或子进程之间的通信,或者两个同级进程之间的通信。在所有操作系统shell中都可以看到这种通信的常见示例。当您在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。
发布于 2015-02-17 05:10:40
有用于公共输入和输出的stdin和stdout。
常见的样式是这样的:
input->process->output但是使用管道,它就变成了:
input->process1->(tmp_output)->(tmp-input)->process2->outputpipe是返回两个临时tmp-input和tmp-output的函数,即fd[0]和fd[1]。
https://stackoverflow.com/questions/4812891
复制相似问题