APUE函数笔记七: 进程关系

58 篇文章 0 订阅
49 篇文章 0 订阅

第九章  进程关系:

#include <unistd.h>
pid_t getpgrp(void);
    get pgid (>0)

#include <unistd.h>
pid_t getpgid(pid_t pid);
    getpgid(0) same as getpgid(getpid()) same as getpgrp()
    if error return -1

#include <unistd.h>
int setpgid(pid_t pid, pid_t pgid);
    setpgid(0, pgid) same as setpgid(getpid(), pgid)
    setpgid(pid, 0) same as setpgid(pid, pid)
    if error return -1

#include <unistd.h>
pid_t setsid(void);
    if current process is not a process group leader, 
    will create a new session
    else failed
    if success return pgid, else return -1

#include <unistd.h>
pid_t getsid(pid_t pid);
    getsid(0) same as getsid(getpid())

#include <unistd.h>
pid_t tcgetpgrp(int filedes);
    if error return -1
int tcsetpgrp(int filedes, pid_t pgid);
    if success return 0, else return -1

#include <termios.h>
pid_t tcgetsid(int filedes);
    if error return -1

示例:

#include <stdio.h>
#include <errno.h>
#include <stdlib.h>
#include <unistd.h>
#include <signal.h>

void 
sig_hup(int signo)
{
    printf("SIGHUP received, pid = %d\n", getpid());
}

void 
pr_ids(const char * name)
{
    printf("%s: pid = %d, ppid = %d, pgrp = %d, tpgrp = %d\n", 
           name, getpid(), getppid(), getpgrp(), tcgetpgrp(STDIN_FILENO));
    fflush(stdout);
}

int 
main(void)
{
    char     c;
    pid_t    pid;

    pr_ids("parent");
    if ((pid = fork()) < 0) {
        printf("fork error\n");
        exit(-1);
    }
    else if (pid > 0) {
        sleep(5);
        exit(0);
    }
    else {
        pr_ids("child");
        signal(SIGHUP, sig_hup);
        kill(getpid(), SIGTSTP);
        pr_ids("child");
        if (read(STDIN_FILENO, &c, 1) != 1) {
            printf("read error from controlling TTY, errno = %d\n", errno);
        }
        exit(0);
    }
}

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

void 
pr_ids(const char * info)
{
    printf("\n%s: pid = %d, ppid = %d, pgrp = %d, sid = %d, tpgrp = %d\n", 
           info, getpid(), getppid(), getpgrp(), getsid(0), 
           tcgetpgrp(STDIN_FILENO));
    fflush(stdout);
}

int 
main(void)
{
    pid_t    pid;
    int      c;

    if ((pid = fork()) < 0) {
        printf("fork error\n");
        exit(-1);
    }
    else if (pid > 0) {
        sleep(1);
        printf("parent exit\n");
        exit(0);
    }
    else {
        pr_ids("before");
        sleep(2);
        setsid();
        pr_ids("after");
        exit(0);
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值