Program runs but does not respond

Asked

Viewed 74 times

-1

I am programming a simple TCP/IP server on Linux, but after running it on the terminal, I get no answer, nor even print a line that I should print at the beginning of the program. When compiling does not give indication of errors and/or warnings. The code is:

#include <stdio.h>
#include <errno.h>
#include <sys/socket.h>
#include <resolv.h>
#include <arpa/inet.h>
#include <pthread.h>
#include <stdlib.h>
#include <strings.h>

#define ADRRESS "127.0.0.1"
#define PORT 9999


/*void receive_tcp(int clientfd)
{
    char buffer1[7];
    //char *buffer2;
    int n, i;

    n = read(clientfd, buffer1, sizeof(buffer1));

    for(i=0;i<n;i++)
    {
        printf("%c", buffer1[i]);
    }
}*/

void main()
{
    int sock;
    struct sockaddr_in s1;
    char buffer1[7];
    int n, i;

    printf("A criar socket...");

    if ((sock = socket(AF_INET, SOCK_STREAM, 0)) < 0)
    {
        printf("Erro ao criar socket.");
        exit(1);
    }

    bzero(&s1, sizeof(s1));
    s1.sin_family = AF_INET;
    s1.sin_port = htons(PORT);
    s1.sin_addr.s_addr = INADDR_ANY;

    printf("A ligar ao socket...");

    if (bind(sock, (struct sockaddr*)&s1, sizeof(s1)) != 0)
    {
        printf("Erro ao ligar socket.");
        exit(1);
    }

    printf("A configurar socket...");

    if (listen(sock, 10) != 0)
    {
        printf("Erro ao configurar socket.");
        exit(1);
    }
    printf("A entrar no ciclo...");

    while(1)
    {
        int clientfd;
        struct sockaddr_in client_addr;
        int addrlen=sizeof(client_addr);

        pthread_t thread1;

        printf("À espera de uma nova ligação...");
        clientfd = accept(sock, (struct sockaddr*)&client_addr, &addrlen);
        n = read(clientfd, buffer1, sizeof(buffer1));

        for(i=0;i<n;i++)
        {
            printf("%c", buffer1[i]);
        }

        /*pthread_create(&thread1, 0, receive_tcp, clientfd);       
        pthread_detach(thread1);*/

    }
}
  • Are you sure? Here it gives in errors by all that is side...

  • I have tried here with amendments and is giving timeout: https://ideone.com/oaDRiJ

1 answer

0

Try putting line breaks in your prints: stdout can make "buffering" and hide output

    printf("A criar socket...\n");        // print com quebra de linha
    /* ... */
    printf("A ligar ao socket...\n");     // a quebra de linha forca um flush
    /* ... */
    printf("A configurar socket...\n");   // ou entao faz flush(stdout)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.