Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/linux/25.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在Linux和C中使用管道_C_Linux_Pipe - Fatal编程技术网

在Linux和C中使用管道

在Linux和C中使用管道,c,linux,pipe,C,Linux,Pipe,我正在学习操作系统课程,我们应该学习如何使用管道在进程之间传输数据 我们得到了这段演示如何使用管道的简单代码,但我很难理解它 #include <stdio.h> #include <stdlib.h> #include <unistd.h> main() { int pipefd [2], n; char buff[100] ; if( pipe( pipefd) < 0) { p

我正在学习操作系统课程,我们应该学习如何使用管道在进程之间传输数据

我们得到了这段演示如何使用管道的简单代码,但我很难理解它

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>

main()
{
      int  pipefd [2], n;
      char buff[100] ;


      if( pipe( pipefd) < 0)
      {
        printf("can not create pipe \n");
      }
      printf("read fd = %d, write fd = %d \n", pipefd[0], pipefd[1]);
      if ( write (pipefd[1],"hello world\n", 12)!= 12)
      {
        printf("pipe write error \n");
      }
      if(  ( n = read ( pipefd[0] , buff, sizeof ( buff)  ) ) <= 0 )
      {
        printf("pipe read error \n");
      }
      write ( 1, buff, n ) ;
exit (0);
  }
写函数做什么?它似乎将数据发送到管道,并将其打印到屏幕上,至少在第二次调用write函数时,它会这样做

有没有人对一些好的网站有什么建议,可以帮助你了解一些主题,比如这个、FIFO、信号、C中使用的其他基本linux命令?

的第一个参数是要写入的对象


在第一个调用中,代码正在写入管道pipefd[1]的一端。在第二个调用中,它将写入文件描述符1,在POSIX兼容系统中,该描述符始终是控制台的标准输出。文件描述符2是标准错误,值得一提。

该函数创建一个管道,并将其端点文件描述符存储在pipefd[0]和pipefd[1]中。你在一端写的任何东西都可以从另一端读,反之亦然。第一个写调用将hello world写入pipefd[1],而读调用从pipefd[0]读取相同的数据。然后,第二个write调用将该数据写入文件描述符1,默认情况下为STDOUT,这就是您在屏幕上看到它的原因


管道一开始可能会令人困惑。当您读/写更多使用它们的代码时,它们将变得更容易理解。我推荐W.Richard Stevens《UNIX环境中的高级编程》作为一本理解它们的好书。我记得,它有很好的代码示例。

程序通过调用创建管道。管道有一个打开的文件描述符用于读取pipefd[0],还有一个打开的文件描述符用于写入pipefd[1]。程序首先将hello world写入管道的写入端,\n然后从管道的读取端读取消息。然后通过调用文件描述符1将消息写入控制台标准输出

提供有关Unix/Linux IPC的一些好信息。你会经常找到他其他指南的参考资料

我发现Bruce Molay是一本关于Unix/Linux系统编程的优秀书籍