简体   繁体   中英

Reading and writing into the same file using a named pipe in C

More specifically, the program is supposed to emulate the bash command cat file| grep $keyword > file cat file| grep $keyword > file . What I've done is: In the parent I read every character from the file and format them into lines which I then send to the named pipe, then in the child write the lines containing the keyword into the original file.

However, I receive a segmentation fault error when attempting to read the second character from the original file, which I assume is because the parent is waiting for the child to write in the original file instead of instead of reading the contents of said file.

Any help with the implementation/explanation of why exactly the error occurs would be great.

#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");
}

You're segfaulting because you're trying to read a byte into c . However, c is an uninitialized global pointer and thus it's equal to NULL . Trying to read data at that location is therefore an invalid use of memory.

What you do instead is declare

char c;

and then

read(fd_r,&c,1)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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