什么是fork什么pipe?任何解释为什么需要使用它们的场景将不胜感激.C fork和pipeC 之间有什么区别?我们可以在C++中使用它们吗?
我需要知道这是因为我想在C++中实现一个程序,它可以访问实时视频输入,转换其格式并将其写入文件.对此最好的方法是什么?我已经使用了x264.到目前为止,我已经在文件格式上实现了转换部分.现在我必须在实时流上实现它.使用管道是个好主意吗?在另一个进程中捕获视频并将其提供给另一个进程?
Vij*_*hew 59
管道是进程间通信的机制.通过一个进程写入管道的数据可以由另一个进程读取.创建管道的原语是pipe函数.这会创建管道的读写端.单个进程使用管道与自身通信并不是很有用.在典型的使用中,进程在forks一个或多个子进程之前创建管道.然后,管道用于父进程或子进程之间或两个兄弟进程之间的通信.在所有操作系统shell中都可以看到这种通信的熟悉示例.当您在shell上键入命令时,它将通过调用生成该命令所表示的可执行文件fork.管道将打开到新的子进程,其输出将由shell读取并打印.此页面包含完整的功能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;
}
}
Run Code Online (Sandbox Code Playgroud)
就像其他的C函数,你可以同时使用fork,并pipe在C++中.
有stdin和stdout用于公共输入和输出。
一个常见的样式是这样的:
input->process->output
Run Code Online (Sandbox Code Playgroud)
但是有了管道,它变成了:
input->process1->(tmp_output)->(tmp-input)->process2->output
Run Code Online (Sandbox Code Playgroud)
pipe是返回两个临时tmp-input和的函数tmp-output,即fd[0]和fd[1]。
| 归档时间: |
|
| 查看次数: |
82483 次 |
| 最近记录: |