通信格式的约定(两种方式)

本文介绍了一种通过管道实现父子进程间通信的方法。具体探讨了两种通信格式:一种是固定长度的字符串交换;另一种则利用字符串前缀指定长度,以便接收方正确解析消息。通过实例展示了如何在实际应用中实现这两种方案。
/*
 * string_type.c
 *
 *  Created on: 2011-11-10
 *      Author: lc
 */

//父子进程使用管道进行通信时,由于读写的字符串长度未知,
//所以要获得有用的信息,就要对读的string和写的string规格进行规定

//1. 规定读写字符串的长度,是定长(规定长度)
//2. 规定前4个字符是字符串长度,后段字符是消息信息(显示长度)

#include <stdio.h>
#include <string.h>

//方法一
//len为规定的消息长度,每次都发送和读取len长度的数据,len不能大于255

void writeLength(int fd, char *info, int len) {
	char buf[255];
	memset(buf, 0, sizeof(buf));
	sprintf(buf, "%s", info);
	write(fd, buf, len);
}

char *readLength(int fd, int len) {
	char buf[255];
	memset(buf, 0, sizeof(buf));
	read(fd, buf, len);
	return buf;
}

//方法二,不规定长度,长度信息包含在信息字符串中

void writeC(int fd, char *info) {
	char buf[255];
	sprintf(buf, "%04d%s", strlen(info), info);

	write(fd, buf, strlen(buf));
}

char *readC(int fd) {
	int i;
	char buf[255];
	memset(buf, 0, strlen(buf));

	read(fd, buf, 4);

	i = atoi(buf);
	read(fd, buf, i);

	return buf;
}
/*
 * pipe_well_format.c
 *
 *  Created on: 2011-11-12
 *      Author: lc
 */
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/wait.h>

void writeC(int fd, char * info);
char *readC(int fd);

int main(int argc, char **argv) {
	int fd[2];
	pid_t id;
	char info[1024];

	if (pipe(fd) < 0) {
		perror("pipe");
		exit(0);
	}

	if ((id = fork()) < 0) {
		perror("fork");
	}

	else if (id == 0) {
		close(fd[1]);
		sleep(2);
		strcpy(info,readC(fd[0]));
		fprintf(stderr,"child receive info from father : %s\n",info);
		close(fd[0]);
		exit(0);
	} else {
		close(fd[0]);

		writeC(fd[1],"hello world,welcome!");

		waitpid(id,NULL,0);
		close(fd[1]);
		exit(0);
	}

	return 0;
}

//使用显示长度的方式通信
void writeC(int fd, char * info) {
	char buf[1024];
	sprintf(buf, "%04d%s", strlen(info), info);
	write(fd, buf, strlen(buf));
}

char *readC(int fd) {
	char buf[1024];

	int count;

	memset(buf, 0, sizeof(buf));
	read(fd,buf,4);
	count = atoi(buf);
	read(fd, buf, count);

	return buf;

}


评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值