多进程下的文件描述符

来源:互联网 发布:网络公司名称大全 编辑:程序博客网 时间:2024/06/05 18:58

传智扫地僧课程学习笔记。



父进程创建子进程后,

父 子进程共享文件描述符,都可以进行操作,

但是父子进程,操作文件的先后顺序,是随机的,



需要强调一点的是,两个进程都有独立的地址空间,都需要close(fd)关掉文件,

简单说,就是,操作的是一个文件表,在这个文件表中,会记录有2个进程在操作,想知道更细节的话,去课程中看,

#include <sys/types.h>#include <unistd.h>#include <stdlib.h>#include <stdio.h>#include <string.h>#include <signal.h>#include <errno.h>#include <signal.h>   #include <sys/stat.h>       #include <fcntl.h>int main(void ){pid_t pid;int fd; signal(SIGCHLD, SIG_IGN);printf("befor fork pid:%d \n", getpid());/*RETURN VALUE       open() and creat() return the new file descriptor, or -1 if an error occurred  (in  which  case,  errno  is  set       appropriately).       */fd  = open("./1.txt", O_RDWR);if (fd == -1){perror("myopen");return -1;}pid = fork(); //errnoif (pid == -1){perror("tile");return -1;}if (pid > 0){printf("parent: pid:%d \n", getpid());//#include <unistd.h>       //ssize_t write(int fd, const void *buf, size_t count);write(fd, "parent", 6);close(fd);//sleep(20);}else if (pid == 0){printf("child: %d, parent: %d \n", getpid(), getppid());write(fd, "child", 5);//sleep(100);close(fd);exit(0);}printf("fork after....\n");return 0;}


0 0
原创粉丝点击