Почему я получаю мусор на этой трубе? - PullRequest
4 голосов
/ 30 ноября 2010

Я использую полнодуплексный код сервера / клиента, который нашел на веб-сайте Oracle:

При написании ./fd_client хахаха, я получаю что-то вроде:

HAHAHA0� $0

В верхнем регистре все в порядке (это то, что сервер должен вернуть), но как, черт возьми, мне избежать этого конечного мусора?

fd_client.c

#include <unistd.h>
#include <stdio.h>
#include <errno.h>
#include <ctype.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <string.h>
#include <stdlib.h>
#include <string.h>
#include <pthread.h>
#include "fullduplex.h" /* For name of the named-pipe */


int main(int argc, char *argv[])
{
    int wrfd, rdfd, numread;
    char rdbuf[MAX_BUF_SIZE];

    /* Check if an argument was specified. */

    if (argc != 2) {
        printf("Usage : %s \n", argv[0]);
        exit (0);
    }

    /* Open the first named pipe for writing */
    wrfd = open(NP1, O_WRONLY);

    /* Open the second named pipe for reading */
    rdfd = open(NP2, O_RDONLY);

    /* Write to the pipe */
    write(wrfd, argv[1], strlen(argv[1]));

    /* Read from the pipe */
    numread = read(rdfd, rdbuf, MAX_BUF_SIZE);

    rdbuf[numread] = '0';

    printf("Full Duplex Client : Read From the  Pipe : %s\n", rdbuf);

    return 0;
}

fd_server.c

#include <unistd.h>
#include <stdio.h>
#include <errno.h>
#include <ctype.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <string.h>
#include <stdlib.h>
#include <string.h>
#include <pthread.h>
#include "fullduplex.h" /* For name of the named-pipe */

int main(int argc, char *argv[])
{
    int rdfd, wrfd, ret_val, count, numread;
    char buf[MAX_BUF_SIZE];

    /* Create the first named - pipe */
    ret_val = mkfifo(NP1, 0666);

    if ((ret_val == -1) && (errno != EEXIST)) {
        perror("Error creating the named pipe");
        exit (0);
    }

    ret_val = mkfifo(NP2, 0666);

    if ((ret_val == -1) && (errno != EEXIST)) {
        perror("Error creating the named pipe");
        exit (0);
    }

    /* Open the first named pipe for reading */
    rdfd = open(NP1, O_RDONLY);

    /* Open the second named pipe for writing */
    wrfd = open(NP2, O_WRONLY);

    /* Read from the first pipe */
    numread = read(rdfd, buf, MAX_BUF_SIZE);

    buf[numread] = '0';

    printf("Full Duplex Server : Read From the pipe : %s \n", buf);

    /* Convert to the string to upper case */
    count = 0;
    while (count < numread) {
        buf[count] = toupper(buf[count]);
        count++;
    }

    /* 
     * Write the converted string back to the second 
     * pipe 
     */    
    write(wrfd, buf, strlen(buf));
}

fullduplex.h

#define NP1     "/tmp/np1"
#define NP2     "/tmp/np2"
#define MAX_BUF_SIZE    255

Ответы [ 3 ]

2 голосов
/ 30 ноября 2010

Это:

buf[numread] = '0';

неверно.Вы хотите:

buf[numread] = '\0';

(То же самое с rdbuf[numread] = '0';.)

2 голосов
/ 30 ноября 2010

Возможно, вы имели в виду:

rdbuf[numread] = '\0';

buf в fd_server.c имеет ту же проблему.

0 голосов
/ 30 ноября 2010

Эти строки выдают неправильный вывод:

buf[numread] = '0';
printf("Full Duplex Server : Read From the pipe : %s \n", buf);

Во-первых, buf[numread] = '0'; Перезаписывает ваш нулевой терминатор.
С этим перезаписанным printf(%s) не знает, где прекратить печать.

Нулевой терминатор сообщает C, где заканчивается строка.
После того, как вы перезаписали его, C больше не знает, где находится конец строки, и печатает вашу строку «HAHAHA», но после этого продолжает печатать мусор.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...