【问题标题】:Creating a pipe in c between two programs在两个程序之间用c创建一个管道
【发布时间】:2016-03-24 22:01:05
【问题描述】:

我一直致力于在两个程序 reader.c 和 writer.c 之间用 c 创建一个管道。我无法获得管道程序工作的输入。管道程序应该接受一个 int,将其发送到编写器程序,然后编写器程序将其输出通过管道传输到读取器程序以进行最终输出。下面是三个类的代码。我想我已经很接近了,但谁能帮我将初始 int 输入 argv[2] 放入 writer 类,然后放入 reader 类?

管道程序(communicat.c)

int main(int argc, char *argv[])
{   
    int fd[2];
    pid_t   childpid;
    int result;

    if (argc != 2) 
    {
            printf("usage: communicate count\n");
            return -1;
    }
    pipe(fd);

    childpid = fork();

    if (childpid == -1)
    {
         printf("Error in fork; program terminated\n");
         return -1;
    }

    if(childpid == 0)
    {
            close(1);
            dup(fd[1]);
            execlp("writer", "writer", fd[1],(char *) NULL);  
    }
    else
    {
           childpid = fork();
    }
    if( childpid == 0)
    {
           close(0);
           dup(fd[0]);
           close(fd[0]);
           close(fd[1]);
           execlp("reader", "reader", (char *) NULL); 
    }
    else
    {
          close(fd[0]);
          close(fd[1]);
          int status;
          wait(&status);
    }
    return(0);
}

阅读器.c

int main()
{
   int count; /* number of characters in the line */
   int c; /* input read */
   count = 0; 
   while ((c = getchar())!= EOF) 
   {
        putchar(c); count++;
        if (count == LINELENGTH) 
        {
              putchar('\n'); count = 0;
        }
   }
   if (count > 0) 
        putchar('\n');
    return 0;
}

作家.c

int main(int argc, char *argv[])
{
     int count; /* number of repetitions */
     int i; /* loop control variable */

    if (argc != 2) 
    {
         printf("usage: writer count\n");
         return -1;
    }
    else count = atoi(argv[1]);

    for (i = 0; i < count; i++) 
    {
        printf("Hello");
        printf("hello");
    }
    return 0; 
}

【问题讨论】:

  • 为什么在执行 writer 之前不关闭管道的文件,就像对 reader 一样?
  • 读写器也无法访问调用程序的argc和argv,他们收到的内容取决于你的exec()函数。

标签: c pipe fork


【解决方案1】:

以这种方式更正代码以执行编写器:

if(childpid == 0)
{
    close(1);
    dup(fd[1]);
    close(fd[0]);
    close(fd[1]);
    execlp("writer", "writer", argv[1], (char *) NULL);  
}

【讨论】:

  • 谢谢,关闭 writer 中的 fd 使其工作。我知道它是那样的小东西。
猜你喜欢
  • 2013-08-28
  • 2015-10-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-10-18
  • 1970-01-01
  • 2011-07-10
  • 1970-01-01
相关资源
最近更新 更多