非命名unix 域 套接字 示例

这个东西和匿名管道就没有什么区别呀

[ssj@main test]$ cat socketpair.c
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <unistd.h>
#include <sys/socket.h>
#include <string.h>

#define MAX 100

int main(void)
{
int sockfd[2],n;
pid_t pid;
char buf[MAX];
bzero(buf,sizeof(buf));

if(socketpair(AF_UNIX,SOCK_STREAM,0,sockfd)==-1)
{perror("Fail to socketpair");exit(1);}

pid=fork();
if(pid<0){perror("Fail to fork");exit(1);}
else if(pid==0)
{
close(sockfd[0]);
strcpy(buf,"hello parent");
n=strlen(buf);

if(write(sockfd[1],buf,n)==-1)
{
perror("Fail to write");
exit(1);
}
printf("child closen");

}
else
{
close(sockfd[1]);

if((n=read(sockfd[0],buf,MAX))==-1)
{
perror("Fail to read");exit(1);
}
//printf("%dn",n);
//n=strlen(buf);
//printf("%dn",n);
buf[n]='';
printf("from child:%sn",buf);

if(wait(NULL)==-1){perror("Fail to wait");exit(1);}

printf("the parent donen");
}
return 0;

}

在打印字符串之前的buf[n]='';只是为了测试,如果不给buf赋初值,打印结果会有所不同,注意字符串的‘’

发表回复

您的电子邮箱地址不会被公开。 必填项已用 * 标注