/*
* 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;
}