#include <sys/time.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <sys/time.h>
#include <netinet/in.h>
#include <unistd.h>
#include <errno.h>
#include <string.h>
#include <stdlib.h>
#include <stdio.h>
#include <assert.h>
#include <fcntl.h>
extern int errno;
int main(void) {
struct sockaddr_in server_addr;
socklen_t server_addr_len = sizeof(struct sockaddr_in);
int listen_fd, connected_fd;
int retval;
struct timeval timeout;
char buf[103425];
memset(buf, 'c', 103425);
buf[103424] = '\0';
listen_fd = socket(AF_INET, SOCK_STREAM, 0);
if (listen_fd < 0)
perror("socket() error");
connected_fd = socket(AF_INET, SOCK_STREAM, 0);
if (connected_fd < 0)
perror("socket() error");
if (listen(listen_fd, 5) < 0)
perror("listen() error");
if (fork() == 0) {
struct sockaddr_in originating_addr;
socklen_t originating_addr_len = sizeof(struct sockaddr_in);
int accepted_fd;
/* Accept the connection, wait for it to be closed, then die. */
accepted_fd = accept(listen_fd, (struct sockaddr*) &originating_addr,
&originating_addr_len);
if (accepted_fd < 0)
perror("accept() error");
/* We can use fcntl() to set socket's block mode. */
/*
int fl = fcntl(accepted_fd, F_GETFL, 0);
if (fl == -1)
perror("fcntl() error");
fcntl(accepted_fd, F_SETFL, fl& ~O_NONBLOCK);
*/
timeout.tv_sec = 10;
timeout.tv_usec = 0;
if (setsockopt(accepted_fd, SOL_SOCKET, SO_SNDTIMEO, &timeout,
sizeof(struct timeval)) < 0)
perror("setsockopt() error");
int j;
for (j = 0; j < 10; j++) {
retval = send(accepted_fd, buf, 103425, 0);
if (retval < 0) {
perror("Child: send error");
} else
printf("Child: send %d bytes\n", retval);
}
return 0;
}
if (getsockname(listen_fd, (struct sockaddr*) &server_addr,
&server_addr_len) < 0)
perror("getsockname() error");
if (connect(connected_fd, (struct sockaddr*) &server_addr,
server_addr_len) < 0)
perror("connect() error");
retval = send(connected_fd, buf, 103425, 0);
if (retval == -1) {
perror("Father: send error");
} else
printf("Father: send %d bytes\n", retval);
return 0;
}
|