Why is the code not writting the correct data into the output file XV6

49 Views Asked by At

I am trying to make a function which takes in 3 operations(such as ls, cat, echo) and write the result to the output file. I have created the function which creates 3 new char arrays and store the operation values in it. The issue is that whenever I am calling close(1), my code keeps on waiting and never exits. If I comment that line out, then the file is created but the data inside is random. Here is the code:

`int handle_multiple_pipes(char **operation1, char **operation2, char **operation3){
int fd1[2];
if(pipe(fd1) == -1){
    return -1;
}
int status;
int pid1 = fork();
if (pid1 < 0) {
    return -1;
}
if(pid1 == 0){
    close(1);
    dup(fd1[1]);
    close(fd1[1]);
    close(fd1[0]);
    exec(operation1[0], operation1);
    exit(1);
}
int pid2 = fork();
if (pid2 < 0) {
    return -1;
}
if(pid2 == 0){
    close(0);
    dup(fd1[1]);
    close(fd1[1]);
    close(1);
    dup(fd1[0]);
    close(fd1[1]);
    exec(operation2[0], operation2);
    exit(1);
}
int pid3 = fork();
if (pid3 < 0) {
    return -1;
}
if(pid3 == 0){
    int i=0;
    int type_of_direction = 0;
    char *output_file_path = "NULL";
    while(operation3[i] != 0){
        int redirection = strcmp(operation3[i], ">");
        if (redirection == 0){
            type_of_direction = 1;
            output_file_path = operation3[i+1];
            operation3[i] = '\0';
            operation3[i+1] = '\0';
        }
        i++;
    }
    if (type_of_direction == 0){
        close(0);
        dup(fd1[0]);
        close(fd1[0]);
        close(fd1[1]);
        exec(operation3[0], operation3);
        exit(1);
    }
    else if (type_of_direction == 1){
        printf("IN HERE 0\n");
        int output_file = open(output_file_path, O_CREATE | O_WRONLY);
        printf("IN HERE 1\n");
        close(fd1[0]);
        // close(fd1[1]);
        printf("IN HERE 2\n");
        wait(&status);
        close(1);
        printf("IN HERE 3\n");
        dup(output_file);
        printf("IN HERE 4\n");
        exec(operation3[0], operation3);
        close(output_file);
        exit(1);
    }
}
close(fd1[0]);
close(fd1[1]);
wait(&status);
wait(&status);
wait(&status);
return 1;

} `

I was expecting the correct data to be written in the output file. For example: Input: ls | grep tests | grep user Expected output: usertests 2 15 180504 Current output: The code never exits.

I also tried debugging the code, the execution always stop at close(1). I am using the same execution flow in one other function and that is working. I just cannot understand the problem with this code.

0

There are 0 best solutions below