- 論壇徽章:
- 0
|
本帖最后由 sepqer 于 2015-03-16 15:59 編輯
例如,我在程序開始的時(shí)候open一個(gè)fd,然后fork。子進(jìn)程繼承了這個(gè)fd。那么父進(jìn)程close這個(gè)fd之后,子進(jìn)程是否也需要再次close這個(gè)fd,才能保證引用計(jì)數(shù)正確呢?
實(shí)驗(yàn)代碼如下:
- #include<stdio.h>
- #include<fcntl.h>
- #include<unistd.h>
- #include<sys/types.h>
- #include<sys/wait.h>
- int main()
- {
- int fd=open("m.txt",O_CREAT|O_RDWR|S_IWUSR);
- pid_t id=fork();
- if(id>0)//parent
- {
- int status;
- wait(&status);
- write(fd,"world\n",6);
- }
- else if(id==0)//child
- {
- write(fd,"hello",5);
- }
- close(fd); // 這里是父子進(jìn)程都去close(fd)了
- return 0;
- }
復(fù)制代碼 謝謝! |
|