34.0k views
3 votes
Implement a C program that in a loop listens on a port for incoming TCP requests from clients. For each accepted incoming request it forks a child to read and process the request. The parent process continues to listen and accept incoming TCP requests in an endless loop. The program accepts 2 command line parameters: the port number to listen on, the pathname to a directory that serves as root to all requested files or directories. For example: % ./z123456 9001 www The requests received by the program are of the form: GET pathname where the pathname refers to a file or directory to be se

User Bjh Hans
by
5.0k points

1 Answer

4 votes

Answer:

See explaination

Step-by-step explanation:

include <stdio.h>

#define DATA "connection request. . ."

/*

* This program creating pipe, then forks leading to the child communication to the parent with the help of pipe with one way communication.

* socket (sockets[1], the second socket of the array returned by pipe()) and read from the

* input socket (sockets[0]), but not vice versa.

*/

main()

{

int sockets[2], child;

/* Create a pipe */

if (pipe (sockets) < 0) {

perror("opening stream socket pair");

exit(1);

}

if ((child = fork()) = = -1)

perror("fork");

elseif (child) {

char buf[1024];

/* This is still the parent. It reads the child's message. */

close (sockets[1]);

if (read(sockets[0], buf, 1024) < 0)

perror("reading message");

printf(" -->%s\\", buf);

close(sockets[0]);

}else {

/* This is the child. It writes a message to its parent. */

close (sockets[0]);

if (write (sockets[1], DATA, sizeof(DATA)) < 0)

perror("writing message");

close(sockets[1]);

}

}

User Krysia
by
4.3k points