简体   繁体   中英

Why I can't read from and write to socket with printf and scanf?

I wonder why this code is not working. I mean: When both the server and client are running I can type and type with no result. However, when I kill the client, the server starts outputting everything I previously wrote to the client app.

full server.c: https://pastebin.com/iXSYLZS3

#include <fcntl.h>
#include <unistd.h>
#include <stdio.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>

#define PORT 8080

int main(void)
{
        // some code to initialize connection

        printf("connection accepted!\n");
        fflush(stdout);

        close(0);
        dup(sock);
        while (1) {
                scanf("%s", str);
                printf("%s", str);
                fflush(stdout);
        }

        return(0);
}

full client.c: https://pastebin.com/sFmi72ZP

#include <fcntl.h>
#include <unistd.h>
#include <stdio.h>
#include <string.h>
#include <sys/socket.h>
#include <arpa/inet.h>
 
#define PORT 8080
 
int main(void)
{
        // some code to initialize connection
 
        printf("connected!\n");
        fflush(stdout);
 
        close(1);
        dup(sock);
        while (1) {
                scanf("%s", str);
                printf("%s", str);
                fflush(stdout);
        }
 
        return(0);
}

It may appear to 'work', but that is just by accident. Closing the underlying descriptor of a FILE* and replacing it with another is bound to confuse the FILE implementation at some point (most likely during that important demo)

The safe way is to use fdopen to create a new FILE* from the given socket and then use fscanf / fprintf if you insist on using that.

fdopen is a posix function, but so is dup so I guess you are on a posix system.

It works. I just had to add newline at the end of the string for pipe to be flushed. Eg. I used:

printf("%s\n", str);

instead of:

printf("%s", str);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM