繁体   English   中英

使用管道和进程的Unix C程序问题

[英]Unix C program issue using pipes and processes

这是故事:

用C编写一个创建子进程和Granchild进程(子进程的子进程!)的程序。 父进程应读取文件的内容,该文件的名称将在您运行程序时作为参数。 父亲应将阅读的文本发送给孩子,孩子将转换为在“ o”中找到的字符“ a”。 更改后的文本将把该子级发送给孙子级(孙子级),以计算文本中的行数和'o'字符数,并将结果打印在屏幕上(以及可选的文件output.txt)。

所以我创建了一个带有一些'a'字符的文件,但我无法真正将那些字符转换为'o'。

问题是我应该使用哪种命令进行字符转换?

任何帮助,不胜感激。

到目前为止,这是我所做的:

#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <errno.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
#include <string.h>
int main() {
int fd_1[2],fd_2[2],pointer,pointer2,pid1,pid2,i,n;
char filename[200];
char buffer[500000];

printf("Input filename:");
fflush(stdout);

fflush(stdin);

scanf("%s", filename);

pointer = open(filename, O_RDONLY);
    if (pointer == -1) {
    printf("file does not exist\n");
    }
pipe(fd_1);
if ( pipe(fd_1) == -1) {
    perror("pipe");
    exit(1);    
    }
pid1=fork();

switch(pid1){
    case -1: {
        perror("fork");
        exit(10);
        break;
    }
    case 0: { //child process 
        pipe(fd_2);
        if ( pipe(fd_2) == -1) {
            perror("pipe");
            exit(1);    
        }   
        pid2=fork();
        switch(pid2) {
            case -1: {
                perror("fork");
                exit(10);
                break;
            }
            case 0: { //grandchild process 
                close (fd_2[1]);
                break;
            }
            default: { //child process 
                close (fd_1[1]);
                dup2(fd_1[0],1);
                pointer2 = open(buffer, O_WRONLY);  
                for (i=0; i< sizeof(buffer)  ; i++)
                if (buffer[i] == 'a' ) {
                    buffer[i] = 'o'; 
                }       
                write(fd_1[1], buffer, sizeof(buffer));
                wait(&pid2);
                break;
            }
        }
    }
    default: {  //parent process 
        close (fd_1[0]);
        dup2(fd_1[1],0);    
        n = read(pointer, buffer, 200);
        write(fd_1[1], buffer, n);
        wait(&pid1);
        break;
    }
}
return 0;
}

假设孩子已经将管道读入缓冲区,则类似于:

for (int i = 0; i < bytes_read; ++i)
{
    if (buffer[i] == 'a')
        buffer[i] = 'o';
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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