简体   繁体   中英

printf() after UNIX fork()

I'm working on a very basic client server communication service just to learn the concept. On the server side I have a function that accepts connections and lets the client communicate with the server. Whenever a connected client sends a message to the server, it sends a responding message to the client. On the client side I create one thread that listens to messages/responses from the server. This thread simply runs a loop that checks if read() returns more than 0 bytes if so it prints the message. The other threads handles user input and sending messages to the server.

Now to the question: I have a few lines of code that listens to messages from the server

void readFromServer(int fileDescriptor)
{
    int nOfBytes;
    char buffer[512];
    while(1){
        nOfBytes = read(fileDescriptor, buffer, 512);
        if(nOfBytes > 0)
            printf("Server says: %s \n\n>", buffer);
    }
}

This means that when a message comes from the server I would like to represent it like this

>Serever says: Something

>|

but for some reason what I get is this

>>Server says: Something

|

(| pipeline represents the cursor in the console window)

Does anyone know why this is? And is there any solution to this problem?

Thanks in advance.

EDIT------------> The fork() is done in the main function like this

int pid = fork();
if(pid != 0)
    readFromServer(sock);

Very likely stdio buffering gets in the way. To make stdout unbuffered, use

setvbuf(stdout, 0, _IONBF, 0);

once before starting I/O. This is a C89 function, declared in <stdio.h> . Your manual page has all the details.

The double > in your example output is not explained by the code you presented. Possibly your other thread is also printing to stdout .

The lack of a > at the end is almost certainly because stdout is line-buffered by default, meaning it accumulates output until it receives a newline, and prints it one line at a time. You could work around that by disabling buffering, as Jens suggested, or by calling fflush(stdout) after printing.

Be aware, too, that your usage of read() is questionable. It is not certain to read a whole message from the other side in one call, even if that message is less than the 512 bytes you specify. Also, your loop will go into a spin if the other side closes the network connection, with every read() call immediately returning -1 without blocking.

You are writing out the input prompt ">" from one thread and the server statements from another.

To make the UI you want, you will need to invest development in curses (or termcap) technology, and either thread synchronization or select() system call to read from both keyboard and socket.

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