我一直在努力在两个程序(reader.c和writer.c)之间的c中创建管道。我无法获得管道程序正常工作的输入。管道程序应该接受一个int,将其发送到writer程序,然后将其输出通过管道传输到reader程序以获取最终输出。下面是这三个类的代码。我想我很亲密,但是有人可以帮助我将初始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);
}


Reader.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;
}


作家

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;
}

最佳答案

通过以下方式将代码更正为exec writer:

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

关于c - 在两个程序之间的C中创建管道,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/36210753/

10-11 22:58
查看更多