我如何打印 C 管道中的每个字符串

How can i print every string in C pipes

我卡住了,如何打印 C 管道中的每个字符串。

这样输出

收到字符串:spike

收到字符串:spike

收到字符串:spike

但我想要这样

收到字符串:spike

收到字符串:tom

收到字符串:jerry

#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>

int main(void)
{
    int fd[2], nbytes;
    pid_t childpid;
    char string[3][10] = {
        "spike",
        "tom",
        "jerry"};
    char readbuffer[80];

    pipe(fd);

    if ((childpid = fork()) == -1)
    {
        perror("fork");
        exit(1);
    }

    if (childpid == 0)
    {
        /* Child process closes up input side of pipe */
        close(fd[0]);

        /* Send "string" through the output side of pipe */
        write(fd[1], string, (strlen(string) + 1));
        exit(0);
    }
    else
    {
        /* Parent process closes up output side of pipe */
        close(fd[1]);

        /* Read in a string from the pipe */
        nbytes = read(fd[0], readbuffer, sizeof(readbuffer));
        for (int i = 0; i < 3; i++)
        {
            printf("Received string: %s \n", readbuffer);
        }
    }

    return (0);
}

你犯了几个错误。

首先,child 没有将正确的内容写入管道。 然后你 read() 一个 80 字节的缓冲区,它将包含所有 3 个字符串(假设你已经解决了问题 1)。但是因为你写的字节比字符串长,所以你的读缓冲区中间会有一个零字节。任何打印尝试都会在该零字节处停止。

添加错误处理很重要。您永远不能假设读取或写入会成功。

我稍微修改了您的代码,使其运行得更好(但还不正确):

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <sys/types.h>

int main(void)
{
        int     fd[2], nbytes;
        pid_t   childpid;
        /* added newlines to separate the entries when printing */
        char    string[3][10] = {
                         "spike\n",
                         "tom\n",
                         "jerry\n"
                     };
        char    readbuffer[80];

        pipe(fd);
        
        if((childpid = fork()) == -1)
        {
                perror("fork");
                exit(1);
        }

        if(childpid == 0)
        {
                /* Child process closes up input side of pipe */
                close(fd[0]);

                /* Send "string" through the output side of pipe */
                /* Added a loop here, so all 3 entries are written */
                for (int i = 0; i < 3; ++i) {
                    write(fd[1], string[i], (strlen(string[i])));
                }
                exit(0);
        }
        else
        {
                /* Parent process closes up output side of pipe */
                close(fd[1]);

                /* Read in a string from the pipe */
                /* no loop needed here for now
                   But you'd need to read until you reach EOF.
                   I leave that as an exercise
                */
                nbytes = read(fd[0], readbuffer, sizeof(readbuffer));
                readbuffer[nbytes] = '[=10=]';
                printf("Received string: %s \n", readbuffer);
        }
        
        return(0);
}