Maridiama
Maridiama

Reputation: 21

Use read() to get the name of a file from a pipe and open() it in c

This is all done on a linux machine.

I have a pipe, fp, sending from the parent to the child the name of a file using a buffer.

The buffer is:

char buf[20];

the child has the following code:

{
//we are in the child
    close(fp[1]);
    int fd;
    read(fp[0],buf,20);
    if((fd=(open(buf, O_RDONLY)))==-1) exit(1);
    else exit(0);
    close(fp[0]);
}

Even if I type in the name of a file that exists, I'm getting the exit status of 1. So... this unfortunately doesn't work. The issue is that the buff itself not only does '\n', but also also plenty of '\0', all of which don't actually exist in the name of real file. I've tried replacing the '\n' with a '\0' but that also doesn't work. How can I solve this?

Here's the whole code.

#include <stdlib.h>
#include <unistd.h>
#include <stdio.h>
#include <sys/syscall.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <fcntl.h>
 
 
int main(){
    int fp[2];
 
    if (pipe(fp) < 0){
        printf("error creating pipe\n");
        exit(-1);
    }
 
    int id;
    char buf[20];
 
    id=fork();
 
    //father process here --------------------------------
 
    if (id!=0){
        close(fp[0]);   //closing read
 
        printf("program name: ");
        fflush(stdout);
        read(STDIN_FILENO,buf,20);
        write(fp[1],buf,20);
 
        int waitstatus, exitcode;
 
        wait(&waitstatus);
 
        //check if exited correctly
        if (WIFEXITED(waitstatus))
            exitcode = WEXITSTATUS(waitstatus);
        else
        {
            printf("Bad exit\n");
            return 0;
        }
        if (exitcode==1) printf("error, file doesn't exist\n");
        else printf("file does exist\n");
 
        close(fp[1]);
    }
 
 
 
 
    //child process here --------------------
    else{
        close(fp[1]); //closing write
        int fd;
        read(fp[0],buf,20);
        //write(STDOUT_FILENO, buf, 20);
        if((fd=(open(buf, O_RDONLY)))==-1) exit(1);
        exit(0);
        close(fp[0]);
    }
}

Upvotes: 0

Views: 154

Answers (1)

Ted Lyngmo
Ted Lyngmo

Reputation: 117298

You send the full buf which contains a newline and other indeterminate values. You need to remove the newline and I suggest that you only send what you need on the receiving end.

printf("program name: ");
fflush(stdout);
if(fgets(buf, sizeof buf, stdin)==NULL) return 1;
size_t len = strlen(buf);
buf[len - 1] = '\0';      // remove the newline
write(fp[1], buf, len);   // only send what you actually need

Upvotes: 1

Related Questions