C Pipe() 和 fork()

标签 c

出于学习目的,我用 fork 和管道制作的简单程序有问题。我想要一个将 ppid 发送给父级的子级以输出 ppid 的值并执行两次。但是结果是两个ppid输出是一样的,为什么呢?

#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);
    }
  }
}

最佳答案

程序设计可能存在潜在问题。因为 parent 在等待 child 在第一次迭代中,子进程对 val=1 执行 for 循环并生成另一个进程 通过 fork 。最终会出现三个进程,其中两个进程具有相同的pid 因为其中之一正在执行 for 两次。

关于C Pipe() 和 fork(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9638062/

相关文章:

c - 避免在 C 中使用大型 switch/if block 的编程技术/风格?

c - 访问结构数组会出现段错误

c++ - 分配 char 缓冲区以保存 float 的文本表示

c - 链表创建

java - 当使用 StandardOpenOption.SYNC 打开底层 channel 时,我们是否必须刷新 MappedByteBuffer

c - 全局变量在 C 中神奇地改变值

c - C 语言 Collat​​z 猜想程序中的段错误

c - 如何将文件中的纯文本解析为二维矩阵/数组?

c - 将函数中局部(函数内)变量的引用返回给调用者

c - 指向函数的函数指针返回指向所述函数类型的指针