【发布时间】:2019-08-01 11:22:25
【问题描述】:
所以我对 c 中的管道有 2 个问题:
1:
当我在创建管道后 fork 一个进程以使父进程写入管道而子进程从中读取时,它是如何同步的? :父级总是在子级尝试读取数据之前发送数据,尽管它们同时运行? 为什么我不认为孩子在父母尝试发送数据之前就开始阅读?
2:
这是关于管道的文件描述符,参考下面的代码父进程如何在子进程尚未访问该文件时关闭管道输出文件描述符? em> ,假设父母先开始。
任何帮助将不胜感激,谢谢!
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/wait.h>
#include <stdlib.h>
#define BUFFER_SIZE 256
int main(int argc , char*argv[])
{
pid_t worker_pid ;
int descriptor[2];
unsigned char bufferR[256] , bufferW[256];
/***************************** create pipe ********************/
puts("pipe creation");
if (pipe(descriptor) !=0)
{
fprintf(stderr,"error in the pipe");
exit(1);
}
/***************************** create processes ********************/
puts("now fork processes");
worker_pid = fork(); // fork process
if (worker_pid == -1 ) // error forking processes
{
fprintf(stderr,"error in fork");
exit(2);
}
/*********************** communicate processes ********************/
if (worker_pid == 0) // in the child process : the reader
{
close(descriptor[1]); // close input file descriptor , ok because parent finished writing
read(descriptor[0],bufferR,BUFFER_SIZE);
printf("i'm the child process and i read : %s \n",bufferR);
}
if (worker_pid !=0)
{
// is there any case where child attempts to read before parent writting ?
close(descriptor[0]);// close file descriptor of child before it reads ?
sprintf(bufferW,"i'm the parent process my id is %d , and i wrote this to my child",getpid());
write(descriptor[1],bufferW,BUFFER_SIZE);
wait(NULL);
}
return 0;
}
我预计 问题 1 会有一些情况,输出为:
i'm the child process and i read :
因为父母还没有写它的消息
对于问题 2,我预计会出现以下错误:
子进程中的文件描述符无效,因为父进程已经关闭它(假设父进程总是第一个运行)
但实际输出始终是:
i'm the child process and i read: i'm the parent process my id is 7589, and i wrote this to my child
【问题讨论】:
-
你似乎不明白在
fork()和file descriptors 期间会发生什么,并且同一个文件描述符可以在多个进程中“活动”。我建议阅读一些基本的 fork/IPC 教程。
标签: c linux pipe file-descriptor