美文网首页
linux应用程序进程操作(fork vfork)

linux应用程序进程操作(fork vfork)

作者: 嵌入式工作 | 来源:发表于2018-11-07 11:16 被阅读0次

    1fork ,fork的子进程和父进程同时运行,运行顺序不确定

    2 vfork先运行子进程,再运行父进程

    3 fork 运行如下

    test@ubuntu:~/test$ ./fort 
    i am father :15503 
    i am child :15504 
    test@ubuntu:~/test$ 
    

    fork程序

    #include<unistd.h>
    #include <sys/types.h>
    #include <stdio.h>
    #include <stdlib.h>
    #include <errno.h>
    #include <math.h>
    
    int main(void)
    {
        pid_t child;
        /*创建子程序*/
        if((child=fork())==-1)
        {
            printf("fork error :%d \n",strerror(errno));
            exit(1);
            
        }else if( 0 == child)/*子进程*/
        {
            printf("i am child :%d \n",getpid());
            exit(0);
            
        }else 
        {
            printf("i am father :%d \n",getpid());
            exit(0);
            
        }
    
    }
    
    

    4.vfork,运行如下:

    test@ubuntu:~/test$ gcc -o vf vfork_test.c 
    test@ubuntu:~/test$ ./vf
    child process start...
    i am child 15481
    i am father :15480 
    test@ubuntu:~/test$ 
    

    代码

    #include <unistd.h>
    #include <sys/types.h>
    #include <sys/wait.h>
    #include <stdlib.h>
    #include <stdio.h>
    #include <errno.h>
    
    int main(void)
    {
        
        pid_t child;
        
        
        if((child = vfork())==-1)
        {
            printf("vfork error :%d \n",strerror(errno));
            exit(1);
            
        }else if(0==child)/*子进程优先运行*/
        {
            printf("child process start...\n");
            sleep(2);
            printf("i am child %d\n",getpid());
            exit(0);
        }else 
        {
            printf("i am father :%d \n",getpid());
            exit(0);
        }
        
    }
    
    

    相关文章

      网友评论

          本文标题:linux应用程序进程操作(fork vfork)

          本文链接:https://www.haomeiwen.com/subject/isvmxqtx.html