C pipes write/read priority -
i trying understand pipes , use of fork in c. below example of code calls fork() , then:
- child process: reads
pipe, prints content console. parent process: writes in
pipe"hello world".int main(void) { pid_t pid; int mypipe[2]; /* create pipe. */ if (pipe(mypipe)) { fprintf(stderr, "pipe failed.\n"); return exit_failure; } /* create child process. */ pid = fork(); if (pid == (pid_t)0) { /* child process. close other end first. */ close(mypipe[1]); read_from_pipe(mypipe[0]);//read pipe , print result console return exit_success; } else if (pid < (pid_t)0) { /* fork failed. */ fprintf(stderr, "fork failed.\n"); return exit_failure; } else { /* parent process. close other end first. */ close(mypipe[0]); write_to_pipe(mypipe[1]);//write "hello world" pipe return exit_success; } }
my understanding use pipes, treated files, child process , parent process can communicate. (is correct ?) now, since pipe being used both parent , child, child read empty pipe ? or pipe "hello world" ? , why ? guess random, since child , parent process run simultaneously. true ?
according man 7 pipe, "if process attempts read empty pipe, read(2) block until data available.".
so if read occurs before write, wait until write done.
reciprocally, if read occurs after write, it's obvious return message.
and @ least 1 of these cases must true, because, still according man 7 pipe, "posix.1-2001 says write(2)s of less pipe_buf bytes must atomic", , pipe_buf large enough hold more "hello world".
so read return "hello world".
Comments
Post a Comment