使用C中的命名管道读取和写入同一文件

时间:2020-10-23 22:49:27

标签: c linux bash

更具体地说,该程序应该模拟bash命令cat file| grep $keyword > file。 我要做的是:在父级中,我从文件中读取每个字符并将其格式化为行,然后将其发送到命名管道,然后在子级中,将包含关键字的行写入原始文件中。

但是,当我尝试从原始文件中读取第二个字符时,我收到一个分段错误错误,我认为这是因为父级正在等待子级写入原始文件中,而不是读取其中的内容文件。

任何实施或解释错误发生原因的帮助都会很大。

#include <stdio.h>
#include <string.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>
#include <stdlib.h>
#include <signal.h>
#include <errno.h>

char key[20], *c,line[40];
int fd,fd_r,fd_w,fd_fr,fd_fw,counter=0;

int main(){

pid_t pid;
mkfifo("fifo1",0777);
fgets(key,10,stdin);

int k=0;

if ((pid=fork()) < 0)
        perror("err_fork");

if(pid){ //PARENT

        printf("%d\n",fd_r=open("prog.c",O_RDONLY));
        printf("%d\n",fd_fw=open("fifo1",O_WRONLY));
        while(read(fd_r,c,1)){
                line[k++]=(*c);
                while(read(fd_r,c,1) && ((*c)!='\n'))
                        line[k++]=(*c);
                line[k]=0;
                write(fd_fw,line,strlen(line)+1);
                memset(line,0,sizeof(line));
        }
        close(fd_r);
        close(fd_fw);
}
else{   //CHILD
        printf("%d\n",fd_w=open("prog.c",O_WRONLY));
        printf("%d\n",fd_fr=open("fifo1",O_RDONLY));
        while(read(fd_fr,line,sizeof(line))){
                c=strstr(line,key);
                if(c)
                        write(fd_w,line,strlen(line)+1);
        }
        close(fd_w);
        close(fd_fr);
}

unlink("fifo1");
}

1 个答案:

答案 0 :(得分:2)

您正在执行段错误操作,因为您试图将一个字节读入c。但是,c是未初始化的全局指针,因此它等于NULL。因此,尝试在该位置读取数据是对内存的无效使用。

您要做的是声明

char c;

然后

read(fd_r,&c,1)
相关问题