#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <errno.h>
#include <signal.h> #include <string.h>
#include <assert.h>
#include <iostream> void signal_func(int sig)
{
int saved_errno = errno;
std::cout << "broken pipe!" << std::endl;
errno = saved_errno;
} int main()
{
struct sigaction sa;
sa.sa_handler = signal_func; sigemptyset(&sa.sa_mask);
sa.sa_flags = ; if (sigaction(SIGPIPE, &sa, NULL) < )
{
perror("cannot ignore SIGPIPE"); return -;
} int sockfd = socket(AF_INET, SOCK_STREAM, );
uint16_t port = ;
const char* ip= "192.168.16.105"; assert(sockfd > ); struct sockaddr_in sock_address;
memset(&sock_address, , sizeof(sock_address)); sock_address.sin_family = AF_INET;
sock_address.sin_port = htons();
inet_pton(AF_INET, ip, &(sock_address.sin_addr)); socklen_t sock_len = sizeof(sock_address); int ret = connect(sockfd, (sockaddr*)&sock_address, sock_len);
assert(ret != -); sleep(); // 在sleep之前断开服务端连接 char send_buff[] = "hello server!";
char recv_buff[] = {}; ssize_t ret_1 = send(sockfd, send_buff, strlen(send_buff), ); // 收到对端FIN后依然可以发送成功 不过对端会响应RST if (ret_1 < )
{
std::cout << strerror(errno) << std::endl;
}
else
{
std::cout << "send success!" << std::endl;
} ssize_t ret_2 = recv(sockfd, recv_buff, sizeof(recv_buff), ); if(ret_2 == )
{
std::cout << "remote close connection" << std::endl;
} ssize_t ret_3 = send(sockfd, send_buff, strlen(send_buff), ); // 这时再send会出错 并产生SIGPIPE信号 默认终止进程 if(ret_3 < )
{
if (errno == EPIPE)
{
std::cout << strerror(errno) << std::endl;
}
}
else
{
std::cout << "send success" << std::endl;
} return ;
}
05-04 04:42