映射 Socket 到 Standard IO

演示一下 Unix 系统的 C 程序中如何将 Socket 映射到标准IO。

/* sock2stdio.c
 * Heiher <admin@heiher.info>
 */
 
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <sys/types.h>
#include <sys/socket.h>
 
int main(int argc, char * argv[])
{
	int sock, client, addrlen;
	struct sockaddr_in this_addr, peer_addr;
	unsigned short port = 9000;
	pid_t cpid;
 
	addrlen = sizeof(struct sockaddr_in);
	memset(&this_addr, 0, addrlen);
	memset(&peer_addr, 0, addrlen);
 
	this_addr.sin_port = htons(port);
	this_addr.sin_family = AF_INET;
	this_addr.sin_addr.s_addr = htonl(INADDR_ANY);
 
	sock = socket(AF_INET, SOCK_STREAM, IPPROTO_IP);
	bind(sock, (struct sockaddr*)&this_addr, addrlen);
	listen(sock, 5);
 
	while(-1 != (client=accept(sock, (struct sockaddr*)&peer_addr, &addrlen)))
	{
		cpid = fork();
		if(0 > cpid)
		{
			perror("fork() failed!");
 
			return 1;
		}
		else if(0 == cpid)	/* child */
		{
			close(0);
			close(1);
			close(2);
			dup2(client, 0);
			dup2(client, 1);
			dup2(client, 2);
			close(client);
 
			execl("/bin/dd", "/bin/dd", "bs=1", NULL);
 
			return 0;
		}
	}
 
	return 0;
}
gcc -o sock2stdio sock2stdio.c
./sock2stdio
nc localhost 9000
hello  # Input
hello  # Output

Over!

3 thoughts on “映射 Socket 到 Standard IO”

  1. @婉秋 例如一个HTTP服务器会 fork 一个子进程执行 cgi 程序,它会把客户端连接映射到这个子进程的标准输入输出上,让子进程(CGI程序)直接从 socket 读数据或向 socket 写数据。

Leave a Reply

Your email address will not be published. Required fields are marked *