Tubería C () y horquilla ()

I have a problem with a simple program im making with fork and pipes for learning purpose. I want a child that send the ppid to the parent to output the value of ppid and do this twice. However,the result is two ppid output are the same.Why?

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>

int main()
{
  int   fd[2];  /* for the pipe */
  int   n,pid,ppid,val;
  int   p[5],q[5];

  if (pipe(fd) < 0) {
     printf("Pipe creation error\n");
     exit(1);
  }
  for(val=0;val<2;val++){
    pid = fork();
    if (pid < 0) {
        printf("Fork failed\n");
        exit(1);
    } else if (pid == 0) { /* child */
        ppid = getpid();
        printf("child %d pid:%d \n",val+1,ppid);
        write(fd[1], &ppid, sizeof(ppid));
        sleep(1);
        close(fd[1]);

    } else { /* parent */
   //printf("Parent: pid: ");
        close(fd[1]);
        printf("%d \n",val+1);
        sleep(1);
        n = read(fd[0], &ppid ,sizeof(ppid));
        printf("%d \n",ppid);

        // fflush(stdout);
        close(fd[0]);
        wait(NULL);
        // printf("<parent> I have completed!\n");
        exit(0);
    }
  }
}

preguntado el 09 de marzo de 12 a las 17:03

Huh? You're sending a value from the child to the parent over the pipe and printing it; of course it's exactly the same as in the child. -

Program looks fine to me. Possible confusion: do you want to send the pid, or the ppid ? -

Question is also dsiturbingly similar to another one out there with similar name. -

1 Respuestas

There may be potential problem in the program design. Since the parent waits for the child in the first iteration, the child executes the for loop for val=1 and spawns another process through fork. Eventually there are three process of which two of them will have the same pid as one of them is executing the for twice.

respondido 09 mar '12, 18:03

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.