首页 > 系统服务 > 详细

[学习笔记]父子进程共享文件描述符理解

时间:2015-04-15 16:46:15      阅读:337      评论:0      收藏:0      [点我收藏+]
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include <unistd.h>
#include<errno.h>
#include <signal.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>

//演示父子进程共享文件描述符
//相当于2个fd指向同一块内存空间.
//因为2个进程共享了文件指针偏移量,所以都能向文件中有序写数据

int main(void)
{
    
    pid_t pid;

    int fd;
    fd = open("test.txt", O_WRONLY);
    if (-1 == fd)
    {
        perror("open err");
        exit(0);
    }

    pid = fork();

    if (-1 == pid)
    {
        perror("fork err");
        return 0;
    }
    if (pid > 0)
    {
        write(fd, "parent", 6);
        close(fd);
    }
    if (0 == pid)
    {
        write(fd, "child", 6);
        close(fd);
    }
    
    
    return 0;
}

 

[学习笔记]父子进程共享文件描述符理解

原文:http://www.cnblogs.com/shichuan/p/4428649.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!