Implementation of cp program that prints the number of bytes copied I have written the code for implementation of the cp program that prints the number of bytes copied when the user presses Ctrl-C. Could someone please review this code and provide feedback. Thanks a lot.


#include&lt;stdio.h&gt;
#include&lt;stdlib.h&gt;
#include&lt;unistd.h&gt;
#include&lt;fcntl.h&gt;
#include&lt;error.h&gt;
#include&lt;signal.h&gt;
#define buffer_size 512

void signal_handler(int num);
void write_buf(int des_fd, char *buffer, size_t rlen, int *bytes);
int flag = 0;

void signal_handler(int num)
{
    printf("The caught signal number is : %d\n", num);
    flag = 1;
}

void write_buf(int des_fd, char *buffer, size_t rlen, int *bytes)
{
    int wlen;

    while (1) {
        wlen = write(des_fd, buffer, rlen);
        if (wlen == -1)
            error(1, 0, "error in writing the file\n");
        *bytes = *bytes + wlen;
        buffer = buffer + wlen;
        rlen = rlen - wlen;
        if (rlen == 0)
            break;
    }
}

int main()
{
    int src_fd;
    int des_fd;
    int rlen;
    int bytes;
    char buffer[buffer_size];

    signal(SIGINT, signal_handler);
    src_fd = open("src_text", O_RDONLY);
    if (src_fd == -1)
        error(1, 0, "error in opening the source-file\n");
    des_fd = open("des_txt", O_WRONLY);
    while (1) {
        rlen = read(src_fd, buffer, sizeof(buffer));
        if (rlen == -1)
            error(1, 0, "error in reading the file\n");
        if (rlen == 0)
            break;
        write_buf(des_fd, buffer, rlen, &amp;bytes);
        if (flag == 1)
            printf("The number of bytes copied is :%d\n", bytes);
        flag = 0;
    }
}
```
Do not call printf from the signal handler. It is not signal safe. man sigaction for details.
write_buf is somewhat convoluted. while (rlen &gt; 0) seems more straightforward.

Also, it is forced to write the entire buffer. It means that your program only pays attention to the Ctrl-C in between of writes. You may get more crispy resolution by testing wlen &lt; rlen and inspecting errno; if write was interrupted, it would be EINTR.

void function with an in-out parameter (bytes in your case) is strange to say the least. The void function is not supposed to return anything, and in-out parameters are generally unclean. Just return bytes.
error() is a GNU extension and should not be used in programs intended to be portable. In any case, the pass errno as a second parameter. The user is very interested what exactly was wrong.
If the program was not interrupted, it doesn't print number of bytes copied. Looks like a bug (or a very dubious design decision) to me.