套接字包装通用化ofpipesusedfortwo-waystreamcommunication。
以下内容为匠意雕刻代码http://my.oschina.net/Zeng sai/blog/12583
我今天使用了一次都没玩过的套接字函数socketpair ()。 它负责在进程中创建套接字连接。 乍一看好像没什么,但是配合fork ()使用的话会很开心。 如下所示。
# define string1' messagefromparent '
# define string2' messgaefromchild '
#include sys/types.h
#include sys/socket.h
#include stdio.h
#include errno.h
主() )
{
int sockets[2],child;
char buf[1024];
/*获取the套接字pair * /
if(socketpair(af_UNIX,SOCKcqdzc,
0,sockets(0) {
printf (错误% don socket pairn ),错误);
退出(1;
}
/*创建周期流程* /
if((child=fork ) ) )=-1 ) {
打印机(fork error % d (n ),错误);
退出(1;
}
IF (隐藏!=0()/*thisistheParent ) /
/* close child's end of socket */
关闭(套接字[0];
/*读取消息自池* /
if(read(sockets[1],buf,sizeof ) )0) 0
printf (错误%读取套接字(n ),错误);
退出(1;
}
printf(--%sn )、buf );
/*写消息到池* /
if (写入)套接字[1],
字符串1,sizeof (字符串1 ) )0) {
printf (错误%写入套接字(n ),错误);
退出(1;
}
/*完成* /
关闭(套接字[1];
} else { /* the child */
/* close parent's end of socket */
关闭(套接字[1];
/* send message to parent */
if (write (套接字[0],字符串2,
sizeof (字符串1 ) )0) {
printf (错误%写入套接字(n ),错误);
退出(1;
}
/*获取消息自组件* /
if (读取)套接字[0],
buf,sizeof(buf ) )0) {
printf (错误%读取套接字(n ),错误);
退出(1;
}
printf(--%sn )、buf );
/*完成* /
关闭(套接字[0];
}
}