39.9k views
3 votes
Write a client program that writes a struct with a privateFIFO name (call it FIFO_XXXX, where XXXX is the pid that you got from the getpid( ) function) to the server. Have the server read the privateFIFO name and write a message back to the client. Read the message and print it on the client side

User Kalpeshdeo
by
7.4k points

1 Answer

4 votes

Answer:

client code:

#include <stdio.h>

#include <fcntl.h>

#include <sys/stat.h>

#include <sys/types.h>

#include <unistd.h>

#include <stdlib.h>

#include <string.h>

int main (void)

{

struct values

{

char privateFIFO[14];

int intbuff;

}input;

int fda; // common FIFO to read to write to server

int fdb; // Private FIFO to read from server

int clientID;

int retbuff;

char temp[14];

clientID = getpid();

strcpy(input.privateFIFO, "FIFO_");

sprintf(temp, "%d", clientID);

strcat(input.privateFIFO, temp);

printf("\\FIFO name is %s", input.privateFIFO);

// Open common FIFO to write to server

if((fda=open("FIFO_to_server", O_WRONLY))<0)

printf("cant open fifo to write");

write(fda, &input, sizeof(input)); // write the struct to the server

close(fda);

// Open private FIFO to read

if((fdb=open(input.privateFIFO, O_RDONLY))<0)

read(fdb, &retbuff, sizeof(retbuff));

printf("\\All done\\");

close(fdb);

}

server code:

#include <stdio.h>

#include <errno.h>

#include <fcntl.h>

#include <sys/stat.h>

#include <sys/types.h>

#include <unistd.h>

#include <stdlib.h>

#include <string.h>

struct values

{

char privateFIFO[14];

int intbuff;

}input;

int main (void)

{

int fda; //common FIFO to read from client

int fdb; //private FIFO to write to client

int retbuff;

int output;

// create the common FIFO

if ((mkfifo("FIFO_to_server",0666)<0 && errno != EEXIST))

{

perror("cant create FIFO_to_server");

exit(-1);

}

// open the common FIFO

if((fda=open("FIFO_to_server", O_RDONLY))<0)

printf("cant open fifo to write");

output = read(fda, &input, sizeof(input));

// create the private FIFO

if ((mkfifo(input.privateFIFO, 0666)<0 && errno != EEXIST))

{

perror("cant create privateFIFO_to_server");

exit(-1);

}

printf("Private FIFO received from the client and sent back from server is: %d", output);

//open private FIFO to write to client

if((fdb=open(input.privateFIFO, O_WRONLY))<0)

printf("cant open fifo to read");

write(fdb, &retbuff, sizeof(retbuff));

close(fda);

unlink("FIFO_to_server");

close(fdb);

unlink(input.privateFIFO);

}

Step-by-step explanation:

User Sulay
by
8.4k points