最近观摩了一下Tinyhttpd的源码,Tinyhttpd 是J. David Blackstone在1999年写的一个不到 500 行的超轻量型 Http Server。

官网:http://tinyhttpd.sourceforge.net/

别人的总结:https://github.com/EZLippi/Tinyhttpd

其中有一段:

Linux C stdin stdout 以及重定向

管道、重定向!!

自己来写个demo来学习一下

首先是server_demo.c的代码

#include <unistd.h>
#include <stdio.h>
#include <string.h>
#include <fcntl.h>
int main()
{
	char s[1024] = "hello world";
	int input[2],output[2];
	pid_t pid;
	
	if(pipe(input) < 0)	return 0;
	if(pipe(output) < 0)	return 0;
	pid = fork();
	if(pid == 0)
	{
		dup2(input[0],STDIN_FILENO);//0
		dup2(output[1],STDOUT_FILENO);//1
		
		close(output[0]);
		close(input[1]);
		
		execl("./cgi_demo","./cgi_demo",NULL);
	}
	else if(pid > 0)
	{
		char tmp[1024] = {0};
		close(output[1]);
		close(input[0]);
		
		write(input[1],s,strlen(s));
		read(output[0],tmp,sizeof(tmp));
		printf("recv[%s]\n",tmp);
	}
}

接下来是cgi_demo.c的代码

#include <stdio.h>
#include <string.h>
#include <fcntl.h>
#include <unistd.h>
int main()
{
	int i,len = 11;//strlen("hello world")
	char tmp[1024] = {0};
	/*写法一
	//
	for(i=0;i<len;i++)
		tmp[i] = getchar();
	printf(tmp);
	*/
	
	//写法二
	/*
	read(STDIN_FILENO,tmp,len);//0
	printf(tmp);
	*/
	
	//写法三
	fread(tmp,len,1,stdin);
	printf(tmp);
}

 

编译并执行

gcc cgi_demo.c -o cgi_demo
gcc server_demo.c 


./a.out
#recv[hello world]

其实就是

input[1]->input[0]->stdin->cgi_demo.c

cgi_demo.c->stdout->output[1]->output[0]得到cgi_demo.c的printf

 

试一下多个server_demo程序运行会发生什么呢......

相关文章:

  • 2021-06-06
  • 2022-12-23
  • 2021-09-26
  • 2022-12-23
  • 2021-07-24
  • 2022-12-23
  • 2022-12-23
  • 2022-01-21
猜你喜欢
  • 2021-05-27
  • 2021-07-22
  • 2021-08-08
  • 2021-12-03
  • 2022-12-23
  • 2021-06-24
相关资源
相似解决方案