mrQWERTY
mrQWERTY

Reputation: 4149

Pipe behavior is erratic, not confident about implementation

I am learning about ipc in Linux and trying out pipes. I've set up two pipes between the parent and two child processes. While the data goes through the pipes, I get weird newlines. For instance, the output would sometimes have an extra newline or no newline entirely or even appear on the command line itself. Also, I am unsure whether the way I have set up pipes is correct. I may have overlooked some important details and leave dangling file descriptors.

void run_processes(Command_Args *cmd_args, char *file_paths)
{
        pipe(pipe_RtoA1);
        pipe(pipe_RtoA2);
        pipe(pipe_A1toT1);
        pipe(pipe_A2toT2);
        pipe(pipe_T1toR);
        pipe(pipe_T2toR);

        if (!(pid_A1 = fork())) {
                long read = 0;
                size_t size = 0;
                char *input_str = NULL;
                close(pipe_RtoA1[1]);
                dup2(pipe_RtoA1[0], 0);

                read = getline(&input_str, &size, stdin);
                printf("A1 : %s\n", input_str);
        } else if (!(pid_A2 = fork())) {
                long read = 0;
                size_t size = 0;
                char *input_str = NULL;
                close(pipe_RtoA2[1]);
                dup2(pipe_RtoA2[0], 0);

                read = getline(&input_str, &size, stdin);
                printf("A2 : %s\n", input_str);
        } else {
                FILE *fRtoA1 = NULL;
                FILE *fRtoA2 = NULL;
                fRtoA1 = fdopen(pipe_RtoA1[1], "w");
                fRtoA2 = fdopen(pipe_RtoA2[1], "w");
                close(pipe_RtoA1[0]);
                close(pipe_RtoA2[0]);
                fprintf(fRtoA1, "%s", file_paths);
                fprintf(fRtoA2, "%s", file_paths);
        }

}

I plan on having pipes to other processes, but now I just want to get the pipes from this program R to two other programs A1 and A2 working.

Program R will send file_paths do the pipes and A1 and A2 will print them.

Upvotes: 0

Views: 19

Answers (1)

Tarik
Tarik

Reputation: 11209

You are launching two distinct processes that are ouputting on th standard output in an unpredictable order. Their output may be interlaced. Just to make sure, open output an file for each subprocess, and check the content.

Upvotes: 1

Related Questions