genericServ.c
// 컴파일 할때 아래의 socklib파일을 함께 해야합니다.
// gcc genericServ.c. socklib.c -o genericServ
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>
#include <time.h>
#include <strings.h>
#define port 5084
main()
{
int sock, fd;
sock = make_server_socket(port);
if(sock==-1)
exit(1);
while(1)
{
fd = accept(sock, NULL, NULL);
if(fd==-1)
break;
process_request(fd);
close(fd);
}
}
process_request(int fd)
{
time_t now;
char *cp;
time(&now);
cp = ctime(&now);
write(fd, cp, strlen(cp));
}
// 아래는 fork를 이용해 처리하는 방식입니다.
process_request(fd)
/* send the date out to the client via fd */
{
int pid = fork();
switch(pid) {
case -1: return; /* cannot provide service */
// 포크 오류죠...
case 0: dup2(fd, 1); /* child runs date */
close(fd); /* by redirecting stdout */
execl("/bin/date", "date", NULL);
oops("execlp"); /* or quits */
// 자식프로세스입니다. 이놈으로 요청한 fd를 실행합니다.
default: wait(NULL); /* parent wait for child */
// 부모는 아무것도 안하고 그냥 기다리네요 ...
}
}