zoukankan      html  css  js  c++  java
  • UNIX环境高级编程——创建孤儿进程

    /* 
    创建孤儿进程 
          父进程终止后,向子进程发送挂断信号,又接着发送继续信号。 
    */  
    #include <stdio.h>  
    #include <stdlib.h>  
    #include <string.h>  
    #include <errno.h>  
    #include <signal.h>  
    #include <sys/types.h>  
    #include <unistd.h>  
    /* 处理接受到的挂断信号 */  
    static void sig_hup(int signo)  
    {  
            printf("SIGHUP recvived, pid = %d 
    ", getpid());  
    }  
    /* 打印进程ID、父进程ID、进程组ID、前台进程组ID */  
    static void pr_ids(char* name)  
    {  
            printf("%s: pid = %d, ppid = %d, pgrp = %d, tpgrp = %d 
    ",   
                    name, getpid(), getppid(), getpgrp(), tcgetpgrp(STDIN_FILENO));  
            fflush(stdout);  
    }  
    int main( int agrc, char* argv[])  
    {  
            char c;  
            pid_t pid;  
            pr_ids("parent");  // 打印主进程(父进程)信息  
            if ((pid = fork()) < 0)  
            {  
                printf("fork error
    ");  
                exit(-1);  
            }
    		else if( pid > 0) /* parent */  
            {// 在父进程中  
                sleep(5);  
                exit(0);  
            }
    		else /* child */  
            {// 在子进程中  
                pr_ids("child");  
                signal(SIGHUP, sig_hup); // 绑定挂断信号  
                kill(getpid(), SIGTSTP); // 向自己发送停止信号(Ctrl+Z),暂停进程  
                pr_ids("child");  
                if (read(STDIN_FILENO, &c, 1) != 1)   
                {  
                    printf("read error from controlling TTY, errno = %d
    ", errno);  
                }  
                exit(0);  
            }  
        return 0;  
    }  

    运行结果:

    huangcheng@ubuntu:~$ ./a.out
    parent: pid = 3569, ppid = 2135, pgrp = 3569, tpgrp = 3569
    child: pid = 3570, ppid = 3569, pgrp = 3569, tpgrp = 3569
    SIGHUP recvived, pid = 3570
    child: pid = 3570, ppid = 1, pgrp = 3569, tpgrp = 3569
    


  • 相关阅读:
    EasyUI--messager
    EasyUI--初学
    框架错误汇总
    OGNL调用静态方法和属性
    查询内容在网页里面分页显示+跳页查看
    struts2——通配符
    JavaScript 输出
    JavaScript语法(一)
    Struts+Hibernate+jsp页面 实现分页
    elasticsearch-5.x JAVA API(001)
  • 原文地址:https://www.cnblogs.com/hehehaha/p/6332470.html
Copyright © 2011-2022 走看看