我知道我可以从父进程发送一条消息,并使用管道从子进程使用 read() 接收它,但是如果我想向子进程发送多个不同类型(int、array..)的消息怎么办?是否可以让子进程分别读取?
最佳答案
您可以在enum
中定义各种数据类型
,然后将此enum
附加到您的消息
开头.
typedef enum
{
INT,
CHAR,
FLOAT,
LONG
//other data types
} data_type_t;
比如说,你的信息是:
stackoverflow
并且您需要指示接收方将其作为字符串读取,因此您可以像这样附加它:
1stackoverflow //here 1 indicates CHAR
因此,当 child 阅读它时,它可以提取第一个字符以查看它必须被解释为字符串 (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);
. . .
接收端将提取消息
的第一个位,知道第一个
位,您将能够解释所包含数据的类型。
关于c - 在 C 中使用管道读取多条消息?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22122615/