Reputation: 2122
I understand that I can send a message from parent and receive it using read() from child using pipes, but what if I want to send multiple messages of different types (int, array..) to the child process? Is it possible to let the child process read them separately?
Upvotes: 0
Views: 1236
Reputation: 11649
You can define various data types
in enum
and then append this enum
in the beginning of your message
.
typedef enum
{
INT,
CHAR,
FLOAT,
LONG
//other data types
} data_type_t;
Say, your message is:
stackoverflow
and you need to indicate to the reciever to read it as a string, so you can append it like:
1stackoverflow //here 1 indicates CHAR
So, that one the child reads it, it can extract the 1st character to see that it has to be interpreted as string (CHAR). Use it as:
#define READ 0 /* Read end of pipe */
#define WRITE 1 /* Write end of pipe */
. . .
int fd[2];
char *message = "some random message";
char modified_message[40];
data_type_t type = CHAR; // Say for this message you define the data type as char
sprintf(modified_message, "%d%s", type, message);
write(fd[WRITE], message, strlen(message)+1);
. . .
The receiving end will extract the 1st bit of the message
and knowing the 1st
bit you'll be able to interpret the type of the data contained.
Upvotes: 2