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 \n", getpid());  
}  
/* 打印进程ID、父进程ID、进程组ID、前台进程组ID */  
static void pr_ids(char* name)  
{  
        printf("%s: pid = %d, ppid = %d, pgrp = %d, tpgrp = %d \n",   
                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\n");  
            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\n", 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


转载于:https://www.cnblogs.com/hehehaha/p/6332470.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值