Search code examples
cfile-descriptor

Redirect user input to /dev/null


Hi I'm trying to implement a chat client - server, and want all client's entered text to not be printed locally on the client. So once the user hits enter, the data should be sent to the server only and not to STDOUT. The server then should send this data back to me and all other clients, and only then display this data.

Is this possible ?

When not doing any manipulation on FD I just get duplicate data, and when trying to redirect STDOUT to /dev/null - I still see the user input data on the screen.(after enter key is hit I just want it to clear the screen, maybe?)

With this code I get two lines of output:

void * rcv_from_srv_thread(void * sock_fd_ptr)
{
    char recv_buf[BUF_SIZE] = {};
    int len = 0;
    int sock_fd = *(int *)sock_fd_ptr;


    while (1)
    {
        if ((len = recv(sock_fd, recv_buf, BUF_SIZE, 0)) < 0)
        {
            perror("recv failed");
            return NULL;
        }

        recv_buf[len] = '\0';
        printf("%s", recv_buf);

    }

    assert(0);
    return NULL;

}

void * send_to_srv_thread(void * sock_fd_ptr)
{
    char send_buf[BUF_SIZE] = {};
    int len;
    int sock_fd = *(int *)sock_fd_ptr;

    do
    {
        fgets(send_buf, BUF_SIZE, stdin);

        if ((len = send(sock_fd, send_buf, strlen(send_buf), 0)) < 0)
        {
            perror("send failed");
            return NULL;
        }

    } while(1);

    assert(0);
    return NULL;
}

When running the client:

root@sergey-VirtualBox:~/chat/client# ./client
aaaa
got server IP - 127.0.0.1
asdasd
asdasd
ddd
ddd

Solution

  • It is maybe not the best or cleanest, but at least probably the easiest. You just move up the cursor one line after fgets was run and to the beginning, and the entered line will be overwritten:

    // fgets(…)
    printf("%c[A\r", 27);
    
    // …