簡體   English   中英

c中的fork()和pipes()

[英]fork() and pipes() in c

什么是fork什么是pipe 任何解釋為什么使用它們的場景都將受到贊賞。 C中的forkpipe有什么區別? 我們可以在C ++中使用它們嗎?

我需要知道這是因為我想在C ++中實現一個程序,它可以訪問實時視頻輸入,轉換其格式並將其寫入文件。 對此最好的方法是什么? 我已經使用了x264。 到目前為止,我已經在文件格式上實現了轉換部分。 現在我必須在實時流上實現它。 使用管道是個好主意嗎? 在另一個進程中捕獲視頻並將其提供給另一個進程?

管道是進程間通信的機制。 通過一個進程寫入管道的數據可以由另一個進程讀取。 創建管道的原語是pipe功能。 這會創建管道的讀寫端。 單個進程使用管道與自身通信並不是很有用。 在典型的使用中,進程在它forks一個或多個子進程之前創建一個管道。 然后,管道用於父進程或子進程之間或兩個兄弟進程之間的通信。 在所有操作系統shell中都可以看到這種通信的熟悉示例。 當您在shell上鍵入命令時,它將通過調用fork生成該命令所表示的可執行文件。 管道將打開到新的子進程,其輸出將由shell讀取並打印。 此頁面包含forkpipe函數的完整示例。 為方便起見,代碼如下:

 #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 ++中使用forkpipe

常見的輸入和輸出有stdinstdout

一種常見的風格是這樣的:

input->process->output

但隨着管道,它變成:

input->process1->(tmp_output)->(tmp-input)->process2->output

pipe是返回兩個臨時tmp-inputtmp-output的函數,即fd[0]fd[1]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM