我可以在不使用文件流的情况下编写此代码

时间:2014-10-11 13:26:15

标签: c linux

#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 from Parent!\n");
  fclose (stream);
}

int main (void)
{
  int pid;
  int mypipe[2];

  /* Create the pipe. */
  if (pipe (mypipe))
    {
      printf("Pipe failed.\n");
      return EXIT_FAILURE;
    }

  /* Create the child process. */
  pid = fork ();
  if (pid == 0)
    {
      /* This is the child process.
         Close other end first. */
      close (mypipe[1]);
      read_from_pipe (mypipe[0]);
      return EXIT_SUCCESS;
    }
  else if (pid < 0)
    {
      /* The fork failed. */
      printf ("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;
    }
}

我想编写简单的程序来完成这项任务:

  • 父进程使用pipe()系统调用创建管道。
  • 父进程创建子进程。
  • 父进程发送消息&#34;来自Parent&#34;给孩子。
  • 子进程将消息打印到屏幕上。

此代码创建文件流。我不明白为什么。没有文件流我可以做这件事..?

2 个答案:

答案 0 :(得分:2)

这个答案可能对未来的Google员工有所帮助。

我想这就是你要找的东西。 这是我写的:

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

int main(){     
     int p, f;  
     int rw_setup[2];   
     char message[20];      
     p = pipe(rw_setup);    
     if(p < 0){         
        printf("An error occured. Could not create the pipe.");  
        _exit(1);   
     }      
     f = fork();    
     if(f > 0){
        write(rw_setup[1], "Hello from Parent", 18);    
     }  
     else if(f == 0){       
        read(rw_setup[0],message,18);       
        printf("%s %d\n", message, r_return);   
     }  
     else{      
        printf("Could not create the child process");   
     }      
     return 0;

}

要创建子进程,我们使用fork()。 fork()返回:

  • &lt; 0无法创建子(新)进程

  • = 0表示子流程

  • &gt; 0,即子进程到父进程的进程ID。当&gt; 0父进程将执行时。

pipe()用于将信息从一个进程传递到另一个进程。 pipe()是单向的,因此,对于进程之间的双向通信,可以设置两个管道,每个方向一个。

您可以在此处阅读更多details

答案 1 :(得分:1)

您也可以使用File descriptors

基本上,当您调用pipe()时,操作系统会准备两个文件描述符并将其“名称”写入参数(在这种情况下为mypipe)。

您可以使用这些文件描述符,而无需使用标准操作系统调用打开任何文件流:write()read()close()等。