通过父级到子级的管道传输来计算费率

时间:2019-04-18 08:55:58

标签: pipe

我已经创建了管道,并在父子流程作品之间进行了通信。我无法做的是计算传输速率。例如,如果我有字符串“ Greetings”,并使用父进程将其转移到子进程,则我必须计算每个字符经过的比率,即,字符串通过子进程一个接一个地发送时,比率的计算方式如下字符串长度/总长度* 100。字符串的长度随着每个字符的发送而减少。而且我必须显示这个速率。

#include <sys/types.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#define BUFFER_SIZE 25
#define READ_END 0
#define WRITE_END 1
int main(void)
{
        char write_msg[BUFFER_SIZE] = "Greetings";
        char read_msg[BUFFER_SIZE];
        int fd[2];
        pid_t pid;

        /* create the pipe */
        if (pipe(fd) == -1) {
                fprintf(stderr,"Pipe failed");
                return 1;
        }

        /* fork a child process */
        pid = fork();
        if (pid < 0) { /* error occurred */
                fprintf(stderr, "Fork Failed");
                return 1;
        }
        if (pid > 0) { /* parent process  */
                /* close the unused end of the pipe */
                close(fd[READ_END]);
                /* write to the pipe */
                write(fd[WRITE_END], write_msg, strlen(write_msg)+1);
                /* close the WRITE_END of the pipe */
                close(fd[WRITE_END]);

        }
        else { /* Child process  */
                /* close the unused end of the pipe */
                close(fd[WRITE_END]);
                /* read from the pipe */
                read(fd[READ_END], read_msg, BUFFER_SIZE);
                printf("read %s ",read_msg);
                /* close the READ_END of the pipe */
                close(fd[READ_END]);    

                }
        return 0;
}

0 个答案:

没有答案