每个进程都有一个非负整形表示的唯一进程ID。
init进程是一号进程,是第一个用户态的进程。它负责内核启动以后启动一个unix系统,
它读取的配置文件一般在/etc/rc*、/etc/inittab、/etc/init.d中。
下面的函数返回进程的一些标识:
pid_t getpid(void) //调用进程的进程ID.
pid_t getppid(void) //调用进程的父进程。
uid_t getuid(void) //返回调用进程的实际用户ID。
uid_t geteuid(void) //返回用户的有效用户id
uid_t getgid(void) //调用进程的实际用户组ID。
gid_t getegid(void) //调用进程的实际组ID。
#include "apue.h" int glob = 6; char buf[] = "a write to stdout\n"; int main(void) { int var; pid_t pid; var = 88; if (write(STDOUT_FILENO, buf, sizeof(buf) - 1) != sizeof(buf) - 1) err_sys("write error"); printf("before fork\n"); if ((pid = fork()) < 0) { err_sys("fork error"); }else if (pid == 0) { glob++; var++; }else {sleep(2); } printf("pid = %d, glob = %d, var = %d\n", getpid(), glob, var); exit(0); }
[root@localhost apue]# ./a.out a write to stdout before fork pid = 7656, glob = 7, var = 89 pid = 7655, glob = 6, var = 88 [root@localhost apue]# ./a.out >fort.out [root@localhost apue]# cat fort.out a write to stdout before fork pid = 7671, glob = 7, var = 89 before fork pid = 7670, glob = 6, var = 88
父进程和子进程共享打开的文件。子进程把父进程的所有打开的文件描述符都复制到子进程中。
#include "apue.h" int glob = 6; int main() { int var; pid_t pid; var = 88; printf("before vfork\n"); if ((pid = vfork()) < 0){ err_sys("vfork error"); }else if (pid == 0){ glob++; var++; _exit(0); } printf("pid = %d, glob = %d, var = %d\n", getpid, glob, var); exit(0); }
[root@localhost apue]# vim vforktest.c [root@localhost apue]# gcc vforktest.c [root@localhost apue]# ./a.out before vfork pid = 134513812, glob = 7, var = 89
#include "apue.h" #include <sys/wait.h> void pr_exit(int status); int main(void) { pid_t pid; int status; if ((pid = fork()) < 0) err_sys("error fork"); else if (pid == 0) exit(7); if (wait(&status) != pid) err_sys("wait error"); pr_exit(status); if ((pid = fork()) < 0) err_sys("error fork"); else if (pid == 0) abort(); if (wait(&status) != pid) err_sys("wait error"); pr_exit(status); if ((pid = fork()) < 0) err_sys("error fork"); else if (pid == 0) status /= 0; if (wait(&status) != pid) err_sys("wait error"); pr_exit(status); exit(0); } void pr_exit(int status) { if (WIFEXITED(status)) printf("normal termination,exit status = %d\n", WEXITSTATUS(status)); else if (WIFSIGNALED(status)) printf("abnormal termination, signal number = %d%s\n",WTERMSIG(status), #ifdef WCOREDUMP WCOREDUMP(status) ? " (core file generated)" : ""); #else ""); #endif else if (WIFSTOPPED(status)) printf("child stopped, signal number = %d\n", WSTOPSIG(status)); }
[root@localhost apue]# vim exittest.c [root@localhost apue]# gcc exittest.c exittest.c: In function ‘main’: exittest.c:28: 警告:被零除 [root@localhost apue]# ./a.out normal termination,exit status = 7 abnormal termination, signal number = 6 abnormal termination, signal number = 8