Q:

Problem with C server function

Hi I have a problem with my function, which  responsible for contact between client and server:
#define MAX 1024

void connection(int sock)
{
        char buffer[MAX];
        int newsock;
        int n;
        int r;
if(write(sock,"Hello!\n", 6) < 0)
{
        perror("Error: ");
}

do {
        if(write(sock, "\n> ",3) < 0)
        {
                perror(" Error: ");
        }
memset(buffer,'0',MAX); // fill buffer

n = read(sock,buffer,MAX -1 );
if (strncmp("get",buffer,3) == 0)
{
        execl("/usr/bin/top","/usr/bin/top","-n 1");

}
else if (strncmp("quit",buffer,4) == 0)
{
        write(sock, "Exit from program\n",17);
        close(sock);
}

else
{
write(sock,"Wrong order!\n", 12);

}
}
while(n);
}

When client send "get" the program should sends him view from "top" order, unfortunately it does not work in my program. 
Secondly, please judge this code. This is my first server program. I will be very grateful
And finally, how to change function to give clients possibility to action in program after send "get" order.
Regards and Happy New Year!

A:

You are calling exec without calling fork. So you are replacing your entire server process with a copy of top. This is really unlikely to do what you want.
Very likely, you could accomplish your aims by opening a suitable pseudo-file from the /proc file system, reading the information, and sending it into your socket.
If you really want to use top, you have to use pipe, fork and exec(l) to run top, read it's output from a pipe, and then send that output to the client.
It occurs to me that you might be running in an environment in which the server automatically forks you (like some sort of CGI gateway), in which case your problem is that you need to fdopen to move the socket to be descriptor #1 before exec-ing. It would really help if you would tell us all about your environment by editing your question.

