子进程和父进程的关系和示例

子进程一般继承父进程:用户信息、权限、目录信息、信号信息、环境表、共享存储段和资源限制。

例如:文件描述符表(包含偏移量)是可以共享的:

#include <stdio.h>
#include <fcntl.h>
#include <unistd.h>
#include <string.h>
#include <errno.h>
#include <stdlib.h>
#include <sys/wait.h>

int main()
{
        int fd = open("a.txt", O_RDWR);
        if(fd < 0)
        {
                fprintf(stderr, "open error %s\n", strerror(errno));
                exit(1);
        }

        pid_t pid;
        pid = fork();
        if(pid < 0)
        {
                fprintf(stderr, "fork error %s\n", strerror(errno));
                exit(1);
        }
        else if(pid > 0)//parent process
        {
                if(lseek(fd, 0L, 2) < 0)
                {
                        fprintf(stderr, "lseek error: %s\n", strerror(errno));
                        exit(1);
                }
                close(fd);
        }
        else
        {
                sleep(3);
                char *str = "abcdefg";
                write(fd, str, strlen(str));
        }
        close(fd);
        wait(0);
        return 0;
}

上面的程序中,以读写方式打开一个文件a.txt,里面包含了“hello world”内容,之后启动两个进程,父进程先执行,执行时将文件指针偏移至文件末尾,子进程之后执行写入操作,由于子进程共享父进程的文件描述符信息(由于使用的是同一个文件描述符id),所以子进程的写入会根据父进程的偏移之后的位置。最后文件会变为“hello worldabcdefg”

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值