socketpair初识
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <error.h>
#include <errno.h>
#include <sys/socket.h>
#include <stdlib.h>
#define BUF_SIZE 300
int main()
{
int s[2];
char *sBuffer = (char *)malloc(BUF_SIZE);
pid_t pid;
char sContent[200];
socketpair(AF_UNIX,SOCK_STREAM,0,s);
pid = fork();
if(pid>0)
{
close(s[1]);
printf("master的使用socket是%d,关掉是是%d\n",s[0],s[1]);
sprintf(sContent,"worker%d!开门!查水表!!!我是master%d",pid,getpid());
write(s[0],sContent,strlen(sContent));
sleep(1);
read(s[0], sBuffer , BUF_SIZE );
printf("master%d听到:%s\n",getpid(),sBuffer);
}
else
{
close(s[0]);
printf("worker的使用socket是%d,关掉是是%d\n",s[1],s[0]);
read(s[1], sBuffer , BUF_SIZE );
printf("worker%d听到:%s\n",getpid(),sBuffer);
sprintf(sContent,"master%d!我家水表在外面!!!我是worker%d",getppid(),getpid());
write(s[1],sContent,strlen(sContent));
}
return 0;
}
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <error.h>
#include <errno.h>
#include <sys/socket.h>
#include <stdlib.h>
#define BUF_SIZE 300
int main()
{
int s[2];
char *sBuffer = (char *)malloc(BUF_SIZE);
pid_t pid;
char sContent[200];
socketpair(AF_UNIX,SOCK_STREAM,0,s);
pid = fork();
if(pid>0)
{
close(s[1]);
printf("master的使用socket是%d,关掉是是%d\n",s[0],s[1]);
sprintf(sContent,"worker%d!开门!查水表!!!我是master%d",pid,getpid());
write(s[0],sContent,strlen(sContent));
sleep(1);
read(s[0], sBuffer , BUF_SIZE );
printf("master%d听到:%s\n",getpid(),sBuffer);
}
else
{
close(s[0]);
printf("worker的使用socket是%d,关掉是是%d\n",s[1],s[0]);
read(s[1], sBuffer , BUF_SIZE );
printf("worker%d听到:%s\n",getpid(),sBuffer);
sprintf(sContent,"master%d!我家水表在外面!!!我是worker%d",getppid(),getpid());
write(s[1],sContent,strlen(sContent));
}
return 0;
}
收藏于 2012-08-09
来自于百度空间