|
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
int main()
{
int data_processed;
int file_pipes[2];
const char some_data[]="123";
char buffer[BUFSIZ+1];
int fork_result;
memset(buffer,'\0',sizeof(buffer));
if(pipe(file_pipes)==0) {
fork_result=fork();
if(fork_result==-1) {
fprintf(stderr,"fork failure");
exit(EXIT_FAILURE);
}
/*here we wil jugde the parent and the child process*/
if(fork_result==0) {
/*child process*/
#ifdef DEBUG
printf("see here child id:%d\n",getpid());
#endif
data_processed=read(file_pipes[0],buffer,BUFSIZ);
printf("read %d bytes:%s\n",data_processed,buffer);
exit(EXIT_SUCCESS);
} else {
/*parent process*/
#ifdef DEBUG
printf("see here fork_result:%d\n",fork_result);
printf("compare it with parent id:%d\n",getpid());
#endif
data_processed=write(file_pipes[1],some_data,strlen(some_data)); printf("wrote %d bytes\n",data_processed);
}
}
exit(EXIT_FAILURE);
}
--------------------------------------------------------------------------
运行结果是:
[asnoka@bdolphin:prog]$ ./pipe2
see here child id:3327
see here fork_result:3327
compare it with parent id:3326
wrote 3 bytes
[asnoka@bdolphin:prog]$ read 3 bytes:123
--------------------------------------------------------------------------
现在我想问的是,为什么那个child id和fork_result的关系,他们是相等的,于是我觉得是不是因为那用蓝色标出的那一行,在那里通过分别fork_result的取值,而进入子进程的,但是我总觉得那么既然进入了子进程,那么fork_result的值当是0,或者说如果这个语句不在父进程中执行的话,那么应当是一个随机值,为什么还和fork_result的值一样呢?是不是进入了子进程后,fork_result又被赋值为子进程的pid呢?
请大家帮我看一下,谢谢先!!! |
|