子进程一般继承父进程:用户信息、权限、目录信息、信号信息、环境表、共享存储段和资源限制。
例如:文件描述符表(包含偏移量)是可以共享的:
#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”