09-30-06 12:57 AM
In article <1159572846.387311.63640@h48g2000cwc.googlegroups.com>,
"kimi" <testcpp@gmail.com> wrote:
> Hello,
> I'm new to UNIX programming (and UNIX in general) and am trying to
> learn it to improve my career. I have written the following program
> but do not understand why I get the duplicate line printed out:
>
> Here's the output that I've received and you'll note duplicate "Value
> of PID..." output:
>
> #include <stdio.h>
>
> #include <unistd.h>
> using std::pipe;
>
> #define SIZE 2048
>
> int main(int argc, char **argv)
> {
> int pipefd[2];
> int what_we_read;
> int process_id;
> char buffer_p[SIZE];
>
> if (pipe(pipefd) == -1)
> {
> perror("no pipe");
> exit(1);
> }
> if ((process_id = fork()) < 0)
> {
> perror("no fork");
> exit(1);
> }
>
> printf("\nValue of process_id before if statement: %i\n",
> process_id);
>
> if (process_id == 0)
> {
> printf("\nEntering child process.\n");
> close(pipefd[1]);
> while ((what_we_read = read(pipefd[0], buffer_p, SIZE)) != 0)
> printf("from the pipe the forked child has read %s\n", buffer_p);
> close(pipefd[0]);
> } else {
> printf("\nEntering parent.\n");
> close(pipefd[0]);
> strcpy(buffer_p, "howdyyall");
> write(pipefd[1], buffer_p, strlen(buffer_p)+1);
> close(pipefd[1]);
> }
> exit(0);
> }
>
> Here's the output and you'll note that duplicate "Value of
> process_id..." line:
I don't see any duplicated lines. I see one line that says 0, and
another that says 17706. The first line is printed by the child, the
second one is printed by the parent.
>
> Value of process_id before if statement: 0
>
> Entering child process.
>
> Value of process_id before if statement: 17706
>
> Entering parent.
> from the pipe the forked child has read howdyyall
>
> End of program output.
>
> I can't understand why I get the duplicate line. I clearly have it
> above the if statement starting the child/parent interaction. I
> expected it only to appear once, I don't have a good explanation as to
> why the duplicate line (I know it's not an exact match of course). The
> child and parent execute and then exit, no need for the printf
> statement to repeat.
After fork, you have two processes executing the same program; the only
difference is the value of process_id. They will both execute all the
statements preceding the if(), then they will diverge because the
condition in the if() will be true in the child, false in the parent.
Since the printf() is before the if, they both execute it, so they each
print their value of process_id.
--
Barry Margolin, barmar@alum.mit.edu
Arlington, MA
*** PLEASE post questions in newsgroups, not directly to me ***
*** PLEASE don't copy me on replies, I'll read them in the group ***
[ Post a follow-up to this message ]
|