我知道我可以使用管道从父进程发送消息,并使用read()从子进程接收消息,但是如果我想向子进程发送多个不同类型的消息(int,array..)?是否可以让子进程单独读取它们?
最佳答案
您可以在data types
中定义各种enum
,然后将此enum
附加到message
的开头。
typedef enum
{
INT,
CHAR,
FLOAT,
LONG
//other data types
} data_type_t;
你的信息是:
stackoverflow
您需要指示接收者将其作为字符串读取,这样您就可以像这样附加它:
1stackoverflow //here 1 indicates CHAR
因此,如果子对象读取它,它可以提取第一个字符,以查看它必须被解释为字符串(CHAR)。用作:
#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);
. . .
接收端将提取
message
的第一位,并且知道1st
位,您将能够解释包含的数据类型。