一个fork的小例子

来源:互联网 发布:什么电视软件好 编辑:程序博客网 时间:2024/04/28 08:48

fork() creates a child process that differs from the parent process only in its PID and PPID, and in the fact that resource utilizations are set to 0.  File locks and pending signals are not inherited.

Under Linux, fork() is implemented using copy-on-write pages, so the only penalty that it incurs is the time and memory  required  to  duplicate the parent's page tables, and to create a unique task structure for the child.

1. 这个例子用于证明fork的父子进程共享文件描述符

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


int tmain(void){
        int fd = 0;
        pid_t pid = 0;
        fd = open("./a.txt", O_CREAT|O_RDWR);


        if(pid = fork()){
                int status = 0;
                char buf[1024] = {0};
                wait( &status);
                lseek(fd, 0 , 0);
                read(fd, buf, 1024);
                printf("%s\n", buf);
                close(fd);
                printf("Done\n");
        }else{
                char* buf = "Hello World";
                write(fd, buf, strlen(buf));
        }


        return pid;
}


int main()
{
        int res = tmain();
        printf("In main, %d\n", res);
        return 0;

}


=============================================================================================================

root@bogon /tmp # ./a.out
In main, 0
Hello World
Done
In main, 26506


原创粉丝点击