fork -- 子进程共享父进程打开的文件描述符

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>

#define FILE_PATH "file_point"

int main(int argc, const char *argv[])
{
    pid_t pid;
    //char *sh = malloc(16);
    char sh[16];
    FILE *fp;
     
    char ss[16] = {0};

    strcpy(sh, "hello kitty");

    fp = fopen(FILE_PATH, "r+");
    if (fp == NULL)
    {   
        printf("fopen failed.\n");
        return -1; 
    }   

    pid = fork();
    if (pid < 0)
    {   
        printf("fork failed.\n");
        return 0;
    }   
    else if (pid == 0)
    {   
        sleep(5);
        int ret;
        printf("pid: %d\tThis is child.\n", getpid());
        printf("[child] sh: %p %s\n", sh, sh);

        printf("[Child] ss: %s\n", ss);
        printf("-----------------------\n");
        // 设置读取文件开头
        ret = fseek(fp, SEEK_SET, 0); 
        if (ret < 0)
        {   
            perror("[child] fseek..");
            exit(-1);
        }   

        char buf[16] = {0};
        ret = fread(buf, 1, strlen(sh), fp);
        if (ret < 0)
        {   
            perror("fread: ");
            return -1; 
        }   
        if (ret == 0)
        {   
            if (feof(fp))
               {   
                   printf("end the file\n");
                   return 0;
               }
            printf("error.\n");
            return -1;
        }

        printf("[child] buf: %s\n", buf);

        exit(0);
    }
    else if (pid > 0)
    {
        printf("pid: %d\tThis is parent.\n", getpid());
        printf("[parent] sh: %p %s\n", sh, sh);

        strcpy(ss, "Hello World");
        printf("[Parent] ss: %s\n", ss);

        fwrite(sh, 1, strlen(sh), fp);

        // 设置读取文件开头
        fseek(fp, SEEK_SET, 0);

        char buf[16] = {0};
        int ret = fread(buf, 1, strlen(sh), fp);
        if (ret < 0)
        {
            perror("fread: ");
            return -1;
        }
        if (ret == 0)
        {
            if (feof(fp))
               {
                   printf("end the file\n");
                   return 0;
               }
            printf("error.\n");
            return -1;
        }

        printf("[parent] buf: %s\n", buf);
    }

    int rt;
    pid_t pd = wait(&rt);
    printf("Child %d exit states %d\n", pd, rt);
    return 0;
}

 

1、在fork 之前 先给sh 赋值, 子进程和父进程共享代码段,数据段 ,堆栈等

2、fork之后父进程中赋值ss, 写时复制,子进程无法读取ss数据,父进程独有

3、文件描述符共享

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值