Эта программа на стороне сервера запрашивает у пользователя размер массива, элементы массива и целочисленное значение для поиска в массиве. Если найдено, он печатает сообщение типа «Значение 87 находится в позиции индекса 4» и отправляет его обратно клиенту. Мне удалось придумать следующий код для сервера и клиента. Тем не менее, как я могу отправить результат поиска, такой как «Значение 87 происходит в позиции индекса 4» обратно на сервер от клиента?
Код клиента:
#include <stdio.h>
#include <errno.h>
#include <fcntl.h>
#include <unistd.h>
#include <string.h>
#include <stdlib.h>
#include <sys/errno.h>
#include <sys/stat.h>
#include <sys/types.h>
#define MAX_SIZE 10 //maximum array size
int main (void)
{
int fda; // to write to server
int fdb; // to read response from server
struct{
int size;
int i;
int arr[MAX_SIZE];
} input;
if((fda=open("FIFO_to_server", O_WRONLY))<0)
printf("cant open fifo to write");
printf("Client: Please enter size of the array: ");
scanf("%d", &input.size);
printf("Enter the elements of the array: ");
for(i=0; i<size; i++)
{
scanf(%d", &arr[i]);
}
write(fda, &input, sizeof(input));
close(fda);
printf("\nClient: Got the array sent, now waiting for response ");
if((fdb=open("FIFO_to_client", O_RDONLY))<0)
printf("cant open fifo to read");
close(fdb);
printf ("\nall done!\n");
}
Код сервера
#include <stdio.h>
#include <errno.h>
#include <fcntl.h>
#include <unistd.h>
#include <string.h>
#include <stdlib.h>
#include <sys/errno.h>
#include <sys/stat.h>
#include <sys/types.h>
int main (void)
{
int fda; // to read from client
int fdb; // to write
int i;
int toSearch;
int found;
int finish;
/* Create the fifos and open them */
if ((mkfifo("FIFO_to_server",0666)<0 && errno != EEXIST))
{
perror("cant create FIFO_to_server");
exit(-1);
}
if ((mkfifo("FIFO_to_client",0666)<0 && errno != EEXIST))
{
perror("cant create FIFO_to_client");
exit(-1);
}
if((fda=open("FIFO_to_server", O_RDONLY))<0)
printf("cant open fifo to write");
if((fdb=open("FIFO_to_client", O_WRONLY))<0)
printf("cant open file to read");
finish=read(fda, &input, sizeof(input));
printf("Server: just got the array: %d", arr);
printf("\Enter the integer to be searched in the array: ");
found = 0;
for(i=0; i<size; i++)
{
if(arr[i] == toSearch)
{
found = 1;
break;
}
}
if(found == 1)
{
printf("\n%d is found at position %d", toSearch, i + 1);
}
else
{
printf("\n%d is not found in the array", toSearch);
}
return 0;
close(fdb);
unlink("FIFO_to_client");
close(fda);
unlink("FIFO_to_server");
}