Printf having unusual behavior in C program -



Printf having unusual behavior in C program -

i'm creating server in c on ubuntu, i've problem printf function doesn't work. code. i'd terminal prints "dd" programme starts, doesn't 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 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); }

the output printf buffered.

to output immediately, have 2 options:

add newline (\n) end of string (printf("dd\n");). implicitly flushes output stream (i.e. writes out buffered content).

explicitly flush standard output stream after printf statement (fflush(stdout);).

as sec part of question, sec illustration produces output because programme short lived , output buffers flushed when programme exits. otherwise, have same behaviour (try adding sleep(30) statement after lastly close see yourself).

c printf

Comments

Popular posts from this blog

Delphi change the assembly code of a running process -

json - Hibernate and Jackson (java.lang.IllegalStateException: Cannot call sendError() after the response has been committed) -

C++ 11 "class" keyword -