Hi there

I'm having a problem with gcc
The code compiles just fine ,but it doesn't run
I have a printf next to main but it doesn't even do that

The code is supposed to be an http server ,implemented using Berkeley sockets
,but that doesn't really i just want to write a printf in the beginning of the instruction set and see it in the console
So,only need pay attention to main

#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
#define TAMANHO_ERRO 200
#define VECTOR_ERROS 2
#define VERSAO "HTTP/1.1"
#define TAMANHO_TEXTO 30
struct Erros
{
    int estado;
    int codigo;
    char mensagem[TAMANHO_ERRO];
}vec[VECTOR_ERROS];
struct Configuracao
{
    int porta;
    char dir_base[TAMANHO_TEXTO];
    char doc_default[TAMANHO_TEXTO];
} conf;

void Error_Quit(char * msg)
{
    fprintf(stderr, "SERVIDOR: %s\n", msg);
    exit(EXIT_FAILURE);
}

/*ler a configuraco*/
void ler_conf()
{
    FILE *f;
    char dir[TAMANHO_TEXTO], d_default[TAMANHO_TEXTO];
    int porta;
    f = fopen("config.conf", "r");
    if (f) {

        fscanf(f, "%d\n%s\n%s", &porta, dir, d_default); // le os campo da estrutura
        strcpy(conf.dir_base, dir);
        conf.porta = porta;
        //le o documento default

        strcpy(conf.doc_default, d_default);

        fclose(f);
    }
    else
        Error_Quit("\tNao e possivel abrir o ficheiro de configuracao");
}

void
prenche_vector()
{
    int i;
    FILE *f;
    f = fopen("cod_erros.conf", "r");
    if (f)
    {
        for (i = 0; i < VECTOR_ERROS; i++)
        {
            fscanf(f, "%d %d %s\n", &(vec[i].estado), &(vec[i].codigo), vec[i].mensagem);
        }
    }
    else
    {
        Error_Quit("Ficheiro de erros nao existe");
    }
}
int read_linha(int s, char *b, int m)
{
    printf("text");
    int i;

    for (i = 0; i < m; i++)
    {
        /* ler um caractere */
        if (read(s, &b[i], 1) != 1) return (-1);
        /* fim da linha */
        if (b[i] == '\n')
        {
            b[i] = 0;
            return (i);
        }
        /* ignorar o \r do DOS-WINDOWS */
        if (b[i] == '\r') i--;
    }
    b[i] = 0;
    return (-1);
}
int write_linha(int s, char *b)
{
    char *aux = "\n";
    int len = strlen(b);
    if (write(s, b, len) != len) return (-1);
    if (b[len - 1] == '\n') return (len); /* já tinha \n */
    if (write(s, aux, 1) != 1) return (-1);
    return (len);
}
void mensagens_erro(int estado, char * output)
{

    char codigo[TAMANHO_ERRO / 100];
    int j;
    for (j = 0; j < VECTOR_ERROS; j++)
    {
        if (vec[j].estado == estado)
        {
            sprintf(codigo, "%d", vec[j].codigo);

            strcat(output, VERSAO);
            strcat(output, " ");
            strcat(output, codigo);
            strcat(output, " ");
            strcat(output, vec[j].mensagem);
            strcat(output, "\r\n");

            printf("Header :%s", output);

            return;
        }
    }
}

void envia_ficheiro(char * nome, int socket)
{

    char * statusLine = NULL;
    char linha[80];

    char * contentTypeLine = NULL;
    char * entityBody = NULL;

    char *fileNotFound = "File Not Found";
    char *eofString = "\4\4\4\4";
    int ficheiroExiste = 1;
    FILE *f;
    f = fopen(nome, "r");

    if (!f)
    {
        ficheiroExiste = 0;
    }
    if (ficheiroExiste == 1)
    {
        mensagens_erro(1, statusLine);

        contentTypeLine = "Content-type: text/html /r/n";

        printf("Content : %s ", contentTypeLine); //
    }
    else
    {
        mensagens_erro(-1, statusLine);
        contentTypeLine = "text/html";
        entityBody = "<HTML><HEAD><TITLE>404 Not Found</TITLE></HEAD><BODY>404 Not Found<br>usage:http://www.snaip.com fileName.html</BODY></HTML>";
    }

    // envia a mensagem de erro
    write_linha(socket, statusLine);
    // envia o tipo de conteudo
    write_linha(socket, contentTypeLine);

    // Envia uma linha em branco para sinalizar o fim dos headers
    write_linha(socket, "\r\n");


    //manda o corpo
    if (ficheiroExiste)
    {
        while (fgets(linha, 81, f))
        {
            write_linha(socket, linha);
        }
        fclose(f);
        write_linha(socket, eofString);
    }
    else
    {
        write_linha(socket, fileNotFound);
        write_linha(socket, eofString);
    }


}

/*Processa o pedido
 * recebe o descritor de socket*/

void processa_pedido(int socket)
{
    char header[TAMANHO_ERRO * 2];
    char * token, * nomeFicheiro;

    //le o header
    read_linha(socket, header, TAMANHO_ERRO * 2);
    printf("pedido : %s", header);

    //parse do header
    token = strtok(header, " ");
    printf("token : %s", token);


    if (strcmp(token, "GET") == 0)
    {
        nomeFicheiro = strtok(NULL, " ");
        printf("ficheiro : %s", nomeFicheiro);
        envia_ficheiro(nomeFicheiro, socket);
    }
    close(socket);
    exit(0);




}

int main(int argc, char** argv)
{

    struct sockaddr_in me, from;
    int newSock, sock = socket(AF_INET, SOCK_STREAM, 0);
    int adl = sizeof (me);
    char dataSize;
    int res;
    
   printf("--------------------------------------------------------------------");
   
    bzero((char *) & me, adl);
    me.sin_family = AF_INET;
    me.sin_addr.s_addr = htonl(INADDR_ANY);
    me.sin_port = htons(conf.porta); /* porta local  a abrir - procede do ficheiro de confs*/
    if (-1 == bind(sock, (struct sockaddr *) & me, adl))
    {
        close(sock);
        puts("Porta de servidor ocupada...");
        exit(1);
    }
    listen(sock, 5);
    for (;;)
    {
        newSock = accept(sock, (struct sockaddr *) & from, &adl);
        if (newSock != -1) /* importante verificar */
        {
            res = fork();
            if (res)

            {
                if (res == -1) puts("Fork Failed...");
                else printf("New Child Server Process, PID=%i\n", res);
                /* Processo PAI continua a receber novas conexoes */
                close(newSock);
            }
            else
            {
                printf("text");
                /* Processo FILHO serve o cliente */
                close(sock);

            }
        }
    }
}

and..it's in portuguese

jephthah commented: first post. you not only used code tags, but you indented your code. there's hope yet :) +2

Try adding \n to your debug printf statements, or follow the printf with fflush(stdout);

fflush(stdout); seems to work ...but why?
I've been working ith c ,c++ and never had to do this.
This also seems to be a cheat beause only the printf seem to work

stdout is a buffered stream, so characters are stored internally (for efficiency) and then output at a later stage.

To get the characters to the actual output device, you can
- print a newline
- use fflush

Asking for input can (IIRC) also cause the buffer to be flushed, but I don't know if that's a guaranteed behaviour.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.