如何在C中使用管道?

时间:2016-05-19 15:17:37

标签: pipe

我尝试编写一个代码,其中应该在共享内存中更新变量。所以,我使用fork()来创建子进程。我遇到的问题是我不知道如何使用管道,因此当达到某个值并且一个进程确定它时,它应该通过使用管道告诉另一个进程输出已完成。我在看很多使用管道的例子,但我仍然不确定如何实现。如果有人能帮我提供一些如何做到这一点的指导,我会非常感激。 这是代码:

`#include <stdio.h>
 #include <stdlib.h>
 #include <unistd.h>
 #include <semaphore.h>
 #include <sys/mman.h>
 #include <sys/types.h>
 #include <sys/wait.h>

    int main(void)
{
int * shared=mmap(NULL, sizeof(int), PROT_READ|PROT_WRITE,MAP_SHARED|MAP_ANONYMOUS, -1, 0);
 printf("Value of the variable at the beginning: %d\n", * shared);
pid_t pid;
pid=fork();

if(pid==0)
{
int a=0;
a=* shared;
a+=3;
 printf("Child process: %d\n", a);
sleep(rand()%10);
}
   else{
 int b=0;
b= * shared;
b+=2;  
 printf("Parent process: %d\n", b);
sleep(rand()%10);
     } 
   }

1 个答案:

答案 0 :(得分:0)

您需要将子进程的输入连接到父进程的输出。 请记住,下面的示例将父级的标准输出重定向到子级的标准输入...如果您希望父级仍然能够打印到控制台,请删除第二个dupclose个调用并使用刚才使用的pipefd [0]作为文件句柄

int main(int argc, char **argv)
{
  int pipefd[2];
  int pid;

  int * shared=mmap(NULL, sizeof(int), PROT_READ|PROT_WRITE,MAP_SHARED|MAP_ANONYMOUS, -1, 0);

  pipe(pipefd);

  pid = fork();
  if (pid == 0)
    {

      dup2(pipefd[0], 0);
      close(pipefd[1]);

      int a=0;
      a=* shared;
      a+=3;
      printf("Child process: %d\n", a);
      sleep(rand()%10);

      // Here you can read from stdin and to get input from parent process 
   }
  else
    {
       int b=0;
       b= * shared;
       b+=2;  
       printf("Parent process: %d\n", b);

       dup2(pipefd[1], 1);
       // At this point you won't be able to output from parent to the console
       // your output will not go to the child
       close(pipefd[0]);
       sleep(rand()%10);          
    }
}