fork 产生一个空的子进程

fork 产生一个空的子进程

调用exec函数簇,清除fork后子进程所有的东西,包括数据区,bbs区,堆区,栈区,代码区,甚至文件描述符和文件指针,成为真正意义的空子进程。利用"写时拷贝(copy-on-write)"技术.

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

    pid_t child_t = 0;
    int val = 1234;
int main(int argc, const char *argv[])
{

    FILE* fp = fopen("1.txt","w+");
/*          

////////////////这段表示不继承进system()进程。/////////////////////////////////////
    int fd = fileno(fp);         
    int flags = fcntl(fd, F_GETFD); 
    flags |= FD_CLOEXEC; 
    fcntl(fd, F_SETFD, flags);

//////////相当于open函数,其中flags参数可以传入O_CLOEXEC标记 [注意:linux 2.6.23才开始支持此标记]/////////////////////
 */
    printf("start.......\n");
    child_t = fork();
    printf("child_t = %d\n",child_t);
    sleep(3);
    if(child_t < 0)
    {
        printf("fork error !\n");
    }
    else if(child_t == 0)
    {
        printf("child progam!\n");

        if(execl("/bin/echo", "", "", NULL)<0)      //调用exec函数库成为空子进程
            perror("Err on execl");
        sleep(30);
        system("lsof | grep /work/test/small_test/1.txt");
        printf("--------------------\n");
        char iTest = 'a';
        int ret = 0;
        if((ret = fwrite(&iTest,sizeof(char),1,fp)) != sizeof(char))
        {
            printf("fwrite error %d\n",ret);
        }
        system("lsof | grep /work/test/small_test/1.txt");
        printf("--------------------\n");
        sleep(5);
        system("lsof | grep /work/test/small_test/1.txt");
        printf("--------------------\n");
    }
    else
    {
        printf("parent progam,child ID is %d\n",child_t);
        system("lsof | grep /work/test/small_test/1.txt");
        printf("--------------------\n");
        fclose(fp);
        system("lsof | grep /work/test/small_test/1.txt");
        printf("--------------------\n");
        sleep(60);

    }

    return 0;
}

 

打印信息

[user:small_test] ./test.i386.elf
start.......
child_t = 8244
child_t = 0
parent progam,child ID is 8244
child progam!

test.i386 8243             user   10u      REG       8,17        0 2359313 /work/test/small_test/1.txt
sh        8246             user   10u      REG       8,17        0 2359313 /work/test/small_test/1.txt
grep      8248             user   10u      REG       8,17        0 2359313 /work/test/small_test/1.txt
--------------------
--------------------


 

你可能感兴趣的:(编程)