定义:
int setpgid(pid_t pid,pid_t pgid);
表头文件:
#include<unistd.h>
说明:
setpgid()将参数pid 指定进程所属的组识别码设为参数pgid 指定的组识别码。如果参数pid为0, 则会用来设置目前进程的组识别码, 如果参数pgid为0, 则会以目前进程的进程识别码来取代。
返回值:
执行成功则返回组识别码, 如果有错误则返回-1, 错误原因存于errno中。
相关函数:
getpgid, setpgrp, getpgrp
错误代码:
EINVAL 参数pgid小于0。
EPERM 进程权限不足, 无法完成调用。
ESRCH 找不到符合参数pid指定的进程。
示例代码:
#include <unistd.h> #include <stdio.h> #include <stdlib.h> int main() { pid_t pid; if ((pid = fork()) < 0) { perror("fork"); exit(1); } else if (pid == 0) { printf("child process PID is: %d ", getpid()); printf("child process PGID is: %d ", getpgrp()); sleep(5); printf("child process PGID is: %d ", getpgrp()); exit(0); } sleep(1); // 改变子进程的组ID为子进程本身 setpgid(pid, pid); sleep(5); printf("parent process PID is: %d ", getpid()); printf("parent process PPID is: %d ", getppid()); printf("parent process PGID is: %d ", getpgrp()); setpgid(getpid(), getppid()); // 改变父进程的组ID为父进程的父进程 printf("parent process PGID has changed to: %d ", getpgrp()); return 0; }
运行结果:
child process PID is: 4932
child process PGID is: 4931
child process PGID is: 4932
parent process PID is: 4931
parent process PPID is: 3486
parent process PGID is: 4931
parent process PGID has changed to: 3486