0% found this document useful (0 votes)
5 views2 pages

Ana

The document is a C program that implements a simple FIFO (named pipe) communication system for sending and receiving messages. It defines two main functions, 'snd' for sending messages and 'rcv' for receiving them, while also handling command-line arguments to determine the operation mode. The program attempts to read an environment variable 'FIFOPATH' and uses it as the FIFO path for communication.

Uploaded by

Thi Quế
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views2 pages

Ana

The document is a C program that implements a simple FIFO (named pipe) communication system for sending and receiving messages. It defines two main functions, 'snd' for sending messages and 'rcv' for receiving them, while also handling command-line arguments to determine the operation mode. The program attempts to read an environment variable 'FIFOPATH' and uses it as the FIFO path for communication.

Uploaded by

Thi Quế
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 2

#include <stdio.

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

#define FIFO_PATH "abc_fifo_name"

void rcv(const char *fifo_path){


//Open the FIFO for reading
char buffer[128];
int fd = open(fifo_path, O_RDONLY);
if (fd == -1){
perror("Failed to open FIFO for reading");
}

//Read the FIFO


ssize_t bytes_read = read(fd, buffer, sizeof(buffer) - 1);
if (bytes_read == -1){
perror("Failed to read from FIFO");
close(fd);
}

//Null-terminate buffer
buffer[bytes_read] = '\0';

printf(buffer);

//Close the FIFO


close(fd);
}

void snd(const char *fifo_path, const char *message){


//Open for writing
int fd = open(fifo_path, O_WRONLY);
if (fd == -1){
perror("Failed to open FIFO for writing");
}

//Write message to the FIFO


ssize_t bytes_written = write(fd, message, sizeof(message));
if (bytes_written == -1){
perror("Failed to write to FIFO");
close(fd);
}

//Close the FIFO


close(fd);
}

int main(int argc, char* argv[]){


char* fifo_name = malloc(sizeof(char)*100);
char* message = malloc(sizeof(char)*100);
char**envp = malloc(sizeof(char)*100);
char*dict = malloc(sizeof(char)*100);
while(**envp){
strncpy(dict, *envp, 8);
if(strcmp(dict,"FIFOPATH") == 0){
printf("%s\n", dict);
}
*envp++;
}

int i = 1;
while(i < argc){
if(strcmp(argv[i], "-s") == 0){
i++;
if(strcmp(fifo_name, "") == 0){
perror("No fifo_name");
return -1;
}
strcpy(message, argv[i]);
snd(fifo_name, message);
}
else if(strcmp(argv[i], "-r") == 0){
if(strcmp(fifo_name, "") == 0){
perror("No fifo_name");
return -1;
}
rcv(fifo_name);
}
i++;
}
}

You might also like