работа с трубами - PullRequest
       4

работа с трубами

0 голосов
/ 30 октября 2011

Я пытаюсь заставить это работать, но безуспешно, в основном мне нужно написать в канал и затем вернуть канал обратно с отправленным мною текстом.У меня есть server.c и client.c, поэтому я запускаю server.c ..., открываю новый терминал, а затем запускаю клиент ... проблема в том, что клиент ничего не делает, когда я его запускаю ... Яя уверен, что что-то упустил .. как закрытие трубы.я не уверен .. Я был бы очень признателен за некоторые рекомендации

server.c

#include <stdio.h>
#include <errno.h>
#include <ctype.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <string.h>
#define PIPE1      "PIPE1"
#define PIPE5      "PIPE5"

#define MAX_BUF_SIZE    255

int main(int argc, char *argv[])
{
    int rdfd1,rdfd2,rdfd3,rdfd4, wrfd1,wrfd2,wrfd3,wrfd4,ret_val, count, numread1,numread2,numread3,numread4;
    char buf1[MAX_BUF_SIZE];
    char buf2[MAX_BUF_SIZE];
    char buf3[MAX_BUF_SIZE];
    char buf4[MAX_BUF_SIZE];

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


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



    ret_val = mkfifo(PIPE5, 0666);

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

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


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


    /* Read from the pipes */
    numread1 = read(rdfd1, buf1, MAX_BUF_SIZE);


    buf1[numread1] = '0';

    printf("Server : Read From the  pipe : %sn", buf1);


    /* 
     * Write the converted content to 
     * pipe 
     */    
   write(wrfd1, buf1, strlen(buf1));

}

client.c

#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <ctype.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#define PIPE1      "PIPE1"
#define PIPE5      "PIPE5"


#define MAX_BUF_SIZE    255


int main(int argc,  char *argv[ ]) {
   pid_t childpid;             
   int error;                  
   int i;                     
   int nprocs;                
           /* check command line for a valid number of processes to generate */

   int wrfd1, rdfd1, numread;
    char rdbuf[MAX_BUF_SIZE];

   if ( (argc != 2) || ((nprocs = atoi (argv[1])) <= 0) ) {
       fprintf (stderr, "Usage: %s nprocs\n", argv[0]);
       return 1; 
   }  



   for (i = 1; i < nprocs;  i++) {  
       /* create the remaining processes */

            if ((childpid = fork()) == -1) {
                  fprintf(stderr, "[%ld]:failed to create child %d: %s\n", (long)getpid(), i, strerror(errno));
                   return 1; 
                } 

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

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


         if (childpid)
         break;

           char string1[100];

            if(sprintf(string1, "This is process %d with ID %ld and parent id %ld\n", i,  (long)getpid(), (long)getppid())) {
              write(wrfd1,string1, strlen(string1));
              }

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

         rdbuf[numread] = '0';

         printf("Full Duplex Client : Read From the Pipe : %sn", rdbuf);    
      } 


   return 0; 
}  

Ответы [ 2 ]

2 голосов
/ 30 октября 2011

Кажется, что и сервер, и клиент читают из PIPE1 и записывают в PIPE5.Разве один из них не должен писать в PIPE1, чтобы другой мог прочитать его с другого конца?

Также, если вы тестируете с ./client 1, ваш цикл for (i = 1; i < nprocs; i++) никогда не будет выполнен.*

И последнее, посмотрите на этот вопрос .Я не совсем уверен, что это относится к вашему коду, но об этом стоит помнить.

1 голос
/ 30 октября 2011

Разве эта строка не должна быть '\0'?

buf1[numread1] = '0';
...