1. 问题:
父进程启动一个socket: socket, bind, listen, accept , 在读取数据之前,启动了一个子进程,那么父子进程都能读取到数据吗?
2. 给出实验程序,server端(程序是从网上copy的,简单修改了下):
#include
#include
#include
#include
#include
#include
#include
#define MAXLINE 4096
int main(int argc, char** argv)
{
int listenfd, connfd;
struct sockaddr_in servaddr;
char buff[4096];
int n;
if( (listenfd = socket(AF_INET, SOCK_STREAM, 0)) == -1 ){
printf("create socket error: %s(errno: %d)\n",strerror(errno),errno);
exit(0);
}
memset(&servaddr, 0, sizeof(servaddr));
servaddr.sin_family = AF_INET;
servaddr.sin_addr.s_addr = htonl(INADDR_ANY);
servaddr.sin_port = htons(6666);
if( bind(listenfd, (struct sockaddr*)&servaddr, sizeof(servaddr)) == -1){
printf("bind socket error: %s(errno: %d)\n",strerror(errno),errno);
exit(0);
}
if( listen(listenfd, 10) == -1){
printf("listen socket error: %s(errno: %d)\n",strerror(errno),errno);
exit(0);
}
if( (connfd = accept(listenfd, (struct sockaddr*)NULL, NULL)) == -1){
printf("accept socket error: %s(errno: %d)",strerror(errno),errno);
close(connfd);
return 0;
}
pid_t pid = fork();
if(pid == 0){
printf("[%d]======waiting for client's request======\n", getpid());
n = recv(connfd, buff, MAXLINE, 0);
buff[n] = '\0';
printf("[%d]recv msg from client: %s\n", getpid(), buff);
}else if( pid > 0){
printf("[%d]======waiting for client's request======\n", getpid());
n = recv(connfd, buff, MAXLINE, 0);
buff[n] = '\0';
printf("[%d] recv msg from client: %s\n", getpid(), buff);
}else {
printf("Error \n");
}
close(connfd);
close(listenfd);
}
3. 客户端程序:
#include
#include
#include
#include
#include
#include
#include
#define MAXLINE 4096
int main(int argc, char** argv)
{
int sockfd, n;
char recvline[4096], sendline[4096];
struct sockaddr_in servaddr;
if( argc != 2){
printf("usage: ./client \n");
exit(0);
}
if( (sockfd = socket(AF_INET, SOCK_STREAM, 0)) < 0){
printf("create socket error: %s(errno: %d)\n", strerror(errno),errno);
exit(0);
}
memset(&servaddr, 0, sizeof(servaddr));
servaddr.sin_family = AF_INET;
servaddr.sin_port = htons(6666);
if( inet_pton(AF_INET, argv[1], &servaddr.sin_addr) <= 0){
printf("inet_pton error for %s\n",argv[1]);
exit(0);
}
if( connect(sockfd, (struct sockaddr*)&servaddr, sizeof(servaddr)) < 0){
printf("connect error: %s(errno: %d)\n",strerror(errno),errno);
exit(0);
}
printf("send msg to server: \n");
fgets(sendline, 4096, stdin);
if( send(sockfd, sendline, strlen(sendline), 0) < 0)
{
printf("send msg error: %s(errno: %d)\n", strerror(errno), errno);
exit(0);
}
close(sockfd);
exit(0);
}
4. 看结果:
5. 结论:
只有一个进程能收到消息,至于内核socket的收包,如果有人知道,请告知小弟。
以上有什么不对的地方,请各位大牛们,给予指点。
阅读(1580) | 评论(0) | 转发(0) |