i working on project class , running few times , working fine. of sudden, after changing text file reading , nothing else, stopped working. ran , ran on forever. added printf top start seeing holding me. when compiled , ran printf didn't activate, nothing happened. when commented out body of code, compiled it, , ran it, printf worked fine. have never seen this. how can happen? here code:
#include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <string.h> #include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> #include <netdb.h> void error(const char *msg) { perror(msg); exit(0); } int main(int argc, char* argv[]) { int sockfd, portno, n; struct sockaddr_in serv_addr; struct hostent *server; file *list = fopen("pwlist1.txt","r"); if (list == null) { printf("file fail\n"); exit(1); } const size_t line_size = 30; char* line = malloc(line_size); char buffer[256]; strcpy(buffer,"failure: "); while (fgets(line, line_size, list) != null && strstr(buffer, "failure:") != null) { portno = 48579; sockfd = socket(af_inet, sock_stream, 0); if (sockfd < 0) error("error opening socket"); server = gethostbyname("elnux1.cs.umass.edu"); if (server == null) { fprintf(stderr,"error, no such host\n"); exit(0); } bzero((char *) &serv_addr, sizeof(serv_addr)); serv_addr.sin_family = af_inet; bcopy((char *)server->h_addr, (char *)&serv_addr.sin_addr.s_addr, server->h_length); serv_addr.sin_port = htons(portno); if (connect(sockfd,(struct sockaddr *) &serv_addr,sizeof(serv_addr)) < 0) error("error connecting"); n = write(sockfd,"bloop",strlen("bloop")); if (n < 0) error("error writing socket"); bzero(buffer,256); n = read(sockfd,buffer,255); if (n < 0) error("error reading socket"); n = write(sockfd,"667057",strlen("667057")); if (n < 0) error("error writing socket"); bzero(buffer,256); n = read(sockfd,buffer,255); if (n < 0) error("error reading socket"); n = write(sockfd,line,strlen(line)); if (n < 0) error("error writing socket"); bzero(buffer,256); n = read(sockfd,buffer,255); if (n < 0) error("error reading socket"); } if (strstr(buffer, "failure:") == null) printf("you did it! word is: %s\n",line); else printf("failure.\n"); close(sockfd); return 0; }
contents of pwlist1.txt:
test hi
the usual reason problem describe (of printf
not outputting when comment in rest of code) stdout
not being flushed. can fix adding explicit flush after printf
.
fflush(stdout);
since not clear question printf
having problem with, flush stderr
measure.
fflush(stderr);