根据网上代码http://blog.csdn.net/zchengdong/article/details/6934466 修改,具体打开的socket情况使用lsof -u username 查看,修改后的代码情况如下,可分别修改读取的s[0],s[1]查看读写情况。
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <errno.h>
#include <errno.h>
#include <sys/socket.h>
#include <stdlib.h>
#define BUF_SIZE 300
int main()
{
int s[2];
int w,r;
char string[256] = {0};
char * buf = (char*)calloc(1 , BUF_SIZE);
pid_t pid;
if(socketpair(AF_UNIX,SOCK_STREAM,0,s) == -1 ){
printf("create unnamed socket pair failed:%s\n",strerror(errno) );
exit(-1);
}
if(( pid = fork()) > 0 ){
printf("Parent process's pid is %d\n",getpid());
//close(s[1]);
sprintf(string,"this is test String,coming from pid = %d",getpid());
if(( w = write(s[0] , string , strlen(string) ) ) == -1 ){
printf("Parent write socket error:%s\n",strerror(errno));
exit(-1);
}
if((r = read(s[0], buf , BUF_SIZE )) == -1){
printf("Pid %d read from socket error:%s\n",getpid() , strerror(errno));
}
}else if(pid == 0){
printf("Fork child process successed\n");
printf("Child process's pid is :%d\n",getpid());
//close(s[0]);
sprintf(string,"this is test String,coming from pid = %d",getpid());
if(( w = write(s[1] , string , strlen(string) ) ) == -1 ){
printf("Child write socket error:%s\n",strerror(errno));
exit(-1);
}
if((r = read(s[1], buf , BUF_SIZE )) == -1){
printf("Pid %d read from socket error:%s\n",getpid(), strerror(errno));
}
}else{
printf("Fork failed:%s\n",strerror(errno));
exit(-1);
}
printf("Pid %d read string in same process : %s.[len=%d]\n",getpid(),buf,r);
sleep(300);
exit(0);
}
其逻辑结构如下图: