2013-12-08 2 views
0

Я создал два канала для клиента и сервера, использующих именованные каналы FIFO. Затем я попытался выполнить обмен данными между клиентом и сервером. Связь работает при отправке сообщений с клиента на сервер, но не наоборот. любезную помощь.с использованием именованных каналов для реализации чата в C

вот три кода:

fifo.c (для создания труб)

#include<stdio.h> 
#include<fcntl.h> 
#include<stdlib.h> 
main() 
{ 
int file1,file2; 
int fd; 
char str[256]; 
char temp[4]="how"; 
char temp1[4]; 
file1 = mkfifo("fifo_server",0666); 
if(file1<0) { 
printf("Unable to create a fifo"); 
exit(-1); 
} 

file2 = mkfifo("fifo_client",0666); 

if(file2<0) { 
printf("Unable to create a fifo"); 
exit(-1); 
} 
printf("fifos server and child created successfuly\n "); 
} 

server.c (для отправки и получения от клиента)

#include<stdio.h> 
#include<fcntl.h> 
#include<stdlib.h> 
main() 
{ 
FILE *file1; 
int fifo_server,fifo_client; 
char *choice; 
char *buf; 
if(fork() == 0) 
    { 
     while(1) 
     { 
     fifo_server = open("fifo_server",O_RDWR); 
     if(fifo_server<1) { 
     printf("Error opening file"); 
     } 

     read(fifo_server,choice,sizeof(choice)); 
     printf("%s\n",choice); 
     close(fifo_server); 
     } 
     //sleep(3); 


    } 
else 
{ 
    while(1) 
    { 
     buf = malloc(10*sizeof(char)); 
     scanf("%s",buf); 

     fifo_client = open("fifo_client",O_RDWR); 

     if(fifo_client<1) { 
     printf("Error opening file"); 
     } 



     write(fifo_client,buf,sizeof(buf)); 
     close(fifo_client); 

    } 
} 

close(fifo_server); 
close(fifo_client); 
} 

клиент. c (для отправки и получения с сервера)

#include<stdio.h> 
#include<fcntl.h> 
#include<stdlib.h> 
main() 
{ 
FILE *file1; 
int fifo_server,fifo_client; 
char str[256]; 
char *buf; 
char *choice; 
printf("Welcome to chat\n\n"); 
if(fork() == 0) 
    { 

    while(1) 
    { 
     choice = malloc(10*sizeof(char)); 
     scanf("%s",choice); 

     fifo_server=open("fifo_server",O_RDWR); 
     if(fifo_server < 1) { 
      printf("Error in opening file"); 
      exit(-1); 
      } 

     write(fifo_server,choice,sizeof(choice)); 

     //sleep(10); 
    }  


    } 
else{ 
    while(1) 
    { 


     fifo_client = open("fifo_client",O_RDWR); 
     if(fifo_client<1) { 
     printf("Error opening file"); 
     exit(1); 
     } 

     read(fifo_client,choice,sizeof(choice)); 
     printf("%s\n",choice); 

     /*  
     fifo_client=open("fifo_client",O_RDWR); 

     if(fifo_client < 0) { 
      printf("Error in opening file"); 
      exit(-1); 
      } 

     buf=malloc(10*sizeof(char)); 
     read (fifo_client,buf,sizeof(buf)); 
     printf("\n %s***\n",buf); 
     */ 
    } 

} 

close(fifo_server); 
close(fifo_client); 
} 

ответ

1

Некоторые наблюдения:

  • Вы читали choice, но вы никогда не выделить память для него.
  • Не используйте malloc() и open()/close() на каждой итерации, вместо этого используйте статический буфер символов, например, buf[512] для read() s из сети и write() s, а также (write() strnlen() bytes/символы).

Например, вместо:

char *buf; 
char *choice; 
printf("Welcome to chat\n\n"); 
if(fork() == 0) { 
    while(1) { 
    choice = malloc(10*sizeof(char)); 
    scanf("%s",choice); 

    fifo_server=open("fifo_server",O_RDWR); 
    if(fifo_server < 1) { 
     printf("Error in opening file"); 
     exit(-1); 
    } 
    write(fifo_server,choice,sizeof(choice)); 
} 

ли что-то вроде:

char buf[512]; 
if(fork() == 0) { 
    fifo_server = open("fifo_server", O_RDWR); 
    if(fifo_server < 1) { 
     printf("Error in opening file"); 
     exit(-1); 
    } 
    while(1) { 
    fgets(buf, 512, stdin); 
    write(fifo_server, buf, strnlen(buf, 512)); 
    /* here should be checks for number of bytes/chars written */ 
    } 
} 
0

Только что закончил писать сервера и на стороне клиента программу, которая, кажется, работает! Я создал трубы в терминале в папке. Они называются myPipeC и myPipeS (для клиентов и серверов соответственно).

Это client.c

#include <stdio.h> 
#include <stdlib.h> 
#include <fcntl.h> 
#include <unistd.h> 
#include <string.h> 
#include <errno.h> 

int main(int argc, const char * argv[]) { 
    int myPipeC = open("myPipeC", O_RDWR); 
    int myPipeS = open("myPipeS",O_RDWR); 
    pid_t cpid; 
    char buf[255]; 
    char send[255]; 
    int n; 
    int saveIn = dup(fileno(stdin)); 
    int saveOut = dup(fileno(stdout)); 
    while(1) { 
     if ((cpid = fork()) == 0) { 
      while(1){ 
       while((n=read(myPipeC,&buf,255)) > 0){ 
        write(fileno(stdout), &buf, n*sizeof(char)); 
       } 
      } 
     } else { 
      while(1){ 
       fgets(send, 255,stdin); 
       int len = strlen(send); 
       write(myPipeS,send,(len+1)*sizeof(char)); 
      } 
     } 
    } 
    close(myPipeC); 
    close(myPipeS); 
    fflush(stdin); 
    fflush(stdout); 
    dup2(saveIn,fileno(stdin)); 
    dup2(saveOut, fileno(stdout)); 
    exit(EXIT_SUCCESS); 
} 

server.c

int main(int argc, const char * argv[]) { 
    int myPipeC = open("myPipeC", O_RDWR); 
    int myPipeS = open("myPipeS",O_RDWR); 
    pid_t cpid; 
    char buf[255]; 
    char send[255]; 
    int n; 
    int saveIn = dup(fileno(stdin)); 
    int saveOut = dup(fileno(stdout)); 
    while(1) { 
     if ((cpid = fork()) == 0) { 
      while(1){ 
       while((n=read(myPipeS,&buf,255)) > 0){ 
        write(fileno(stdout), &buf, n*sizeof(char)); 
       } 
      } 
     } else { 
      while(1){ 
       fgets(send, 255,stdin); 
       int len = strlen(send); 
       write(myPipeC,send,(len+1)*sizeof(char)); 
      } 
     } 
    } 
    close(myPipeC); 
    close(myPipeS); 
    fflush(stdin); 
    fflush(stdout); 
    dup2(saveIn,fileno(stdin)); 
    dup2(saveOut, fileno(stdout)); 
    exit(EXIT_SUCCESS); 
}