Reputation: 1065
I'm creating a server in C on Ubuntu, but I've a problem with a printf function which doesn't work. This is the code. I'd like that the terminal prints "dd" as soon as the program starts, but it doesn't do anything. Suggestions?
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <arpa/inet.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <sys/socket.h>
#include <netdb.h>
void main(){
printf("dd");
int ds_sock;
struct sockaddr_in my_addr;
ds_sock=socket(AF_INET,SOCK_STREAM,0);
memset(&my_addr,0,sizeof(my_addr));
my_addr.sin_family=AF_INET;
my_addr.sin_port=htons(25000);
my_addr.sin_addr.s_addr=INADDR_ANY;
bind(ds_sock,(struct sockaddr *)&my_addr,sizeof(my_addr));
listen(ds_sock,3);
printf("dd");
int ds_sock_acc;
struct sockaddr_in addr;
size_t sin_size = sizeof(struct sockaddr_in);
ds_sock_acc = accept(ds_sock,(struct sockaddr *)&addr,&sin_size);
while(ds_sock_acc==-1) {
printf("connessione non riuscita");
ds_sock_acc = accept(ds_sock,(struct sockaddr *)&addr,&sin_size);
}
printf("connessione riuscita");
close(ds_sock);
close(ds_sock_acc);
}
this (client) works as expected:
void main(){
printf("dd");
int ds_sock;
ds_sock = socket(AF_INET, SOCK_STREAM,0);
int ret;
struct sockaddr_in Eaddr;
Eaddr.sin_family = AF_INET;
Eaddr.sin_port = htons(25000);
Eaddr.sin_addr.s_addr=inet_addr("127.0.0.1");
ret = connect(ds_sock,(struct sockaddr *)&Eaddr,sizeof(Eaddr));
while(ret==-1){
printf("Errore nel connect");
ret = connect(ds_sock,(struct sockaddr *)&Eaddr,sizeof(Eaddr));
}
printf("connect OK");
close(ds_sock);
}
Upvotes: 0
Views: 99
Reputation: 19641
The output from printf
will be buffered.
To get the output immediately, you have two options:
Add a newline (\n
) to the end of the string (printf("dd\n");
). This implicitly flushes the output stream (i.e. writes out the buffered content).
Explicitly flush the standard output stream after the printf statement (fflush(stdout);
).
As for the second part of the question, the second example produces output probably only because the program is short lived and output buffers are flushed when the program exits. Otherwise, it would have the same behaviour (try adding a sleep(30)
statement after the last close to see for yourself).
Upvotes: 5
Reputation: 64730
You need to flush your output.
Easiest way:
printf("dd\n");
Better way:
printf("dd");
fflush(stdout);
Upvotes: 3