Question

#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>

int main()
{

int sock, newsock;
    struct sockaddr server_name = {AF_UNIX, "Fred"};
    socklen_t len=sizeof(struct sockaddr)+5;

    if( (sock=socket(AF_UNIX,SOCK_STREAM,0)) ==-1)
    {
        printf("error creating socket");
        return -1;
    }

    if( bind(sock,&server_name,len) != 0 ) //binding
    {

        printf("socket bind error ");
        return -1;
    }


   if(listen(sock,10)!=0)  //set sock to listen
   {
        printf("error listening");
        return -1;
   }

    printf("Waiting for connections....");

   while(1)
   {
        newsock=accept(sock, (struct sockaddr*)NULL, NULL);

        char temp[1000]="gggggg\n";
        write(newsock,temp,strlen(temp));

        write(newsock,temp,strlen(temp));
        close(newsock);

        sleep(1);

   }

return 0;
}

"Waiting for connections..." doesn't appear on my screen. What's the problem? I tried print function everywhere. Nothing shows up..What is the problem? I don't see that I closed stdout..Can anyone help? Thank you.

Was it helpful?

Solution

The standard output is line buffered by default. Your program outputs something without the new line and then enters the loop. You need to add a new line like this:

printf("Waiting for connections....\n");

For similar reasons, the error messages should be output to standard error, because it's not buffered.

fprintf(stderr, "error creating socket\n");

OTHER TIPS

Firstly, you should add '\n' add the end of log:"Waiting for connections....\n", then the log cann't be buffered, and be outputted.

Secondly, your program is error, the correct program is like this:

#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/un.h>

int main()
{

    int sock, newsock;
    struct sockaddr_un server_name;
    socklen_t len= sizeof(server_name);
    unlink("Fred");
    if( (sock=socket(AF_UNIX,SOCK_STREAM,0)) ==-1)
    {
        printf("error creating socket\n");
        return -1;
    }

    server_name.sun_family = AF_UNIX;
    strcpy(server_name.sun_path, "Fred");

    if( bind(sock,(struct sockaddr*)&server_name,len) != 0 ) //binding
    {

        printf("socket bind error \n");
        return -1;
    }


   if(listen(sock,10)!=0)  //set sock to listen
   {
        printf("error listening\n");
        return -1;
   }

   printf("Waiting for connections....\n");

   while(1)
   {
        newsock=accept(sock, (struct sockaddr*)NULL, NULL);

        char temp[1000]="gggggg\n";
        write(newsock,temp,strlen(temp));

        write(newsock,temp,strlen(temp));
        close(newsock);

        sleep(1);

   }

return 0;
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top