linux下的进程等待(wait和waitpid)
linux下的进程等待(wait和waitpid)
wait(等待子进程中断或结束)
表头文件 #include<sys/types.h> #include<sys/wait.h> 定义函数 pid_t wait (int * status); 函数说明: wait()会暂时停止目前进程的执行,直到有信号来到或子进程结束。 如果在调用 wait()时子进程已经结束,则 wait()会立即返回子进程结束状态值。 子进程的结束状态值会由参数 status 返回,而子进程的进程识别码也会一起返回。 如果不在意结束状态值,则参数 status 可以设成 NULL。 子进程的结束状态值请参考 waitpid( ) 如果执行成功则返回子进程识别码(PID) ,如果有错误发生则返回返回值-1。失败原因存于 errno 中。 pid_t pid1; int status=0; i=wait(&status); i返回的是子进程的识别码;PID status中存的是子进程的结束状态;可用WEXITSTATUS(status)得到子进程的exit(3)的状态,那么就是3; waitpid(等待子进程中断或结束) 表头文件 #include<sys/types.h> #include<sys/wait.h> 定义函数 pid_t waitpid(pid_t pid,int * status,int options); 函数说明: waitpid()会暂时停止目前进程的执行,直到有信号来到或子进程结束。 如果在调用 wait()时子进程已经结束,则 wait()会立即返回子进程结束状态值。 子进程的结束状态值会由参数 status 返回,而子进程的进程识别码也会一快返回。 如果不在意结束状态值,则参数 status 可以设成 NULL。 参数 pid 为欲等待的子进程识别码,其他数值意义如下: pid<-1 等待进程组识别码为 pid 绝对值的任何子进程。 pid=-1 等待任何子进程,相当于 wait()。 pid=0 等待进程组识别码与目前进程相同的任何子进程。 pid>0 等待任何子进程识别码为 pid 的子进程。 参数 option 可以为 0 或下面的 OR 组合: WNOHANG 如果没有任何已经结束的子进程则马上返回, 不予以等待。 WUNTRACED 如果子进程进入暂停执行情况则马上返回,但结束状态不予以理会。 子进程的结束状态返回后存于 status,底下有几个宏可判别结束情况: WIFEXITED(status)如果子进程正常结束则为非 0 值。 WEXITSTATUS(status)取得子进程 exit()返回的结束代码,一般会先用 WIFEXITED 来判断是否正常结束才能使用此宏。 WIFSIGNALED(status)如果子进程是因为信号而结束则此宏值为真 WTERMSIG(status) 取得子进程因信号而中止的信号代码,一般会先用 WIFSIGNALED 来判断后才使用此宏。 WIFSTOPPED(status) 如果子进程处于暂停执行情况则此宏值为真。一般只有使用 WUNTRACED 时才会有此情况。 WSTOPSIG(status) 取得引发子进程暂停的信号代码,一般会先用 WIFSTOPPED 来判断后才使用此宏。 如果执行成功则返回子进程识别码(PID) ,如果有错误发生则返回返回值-1。失败原因存于 errno 中。
oot@wl-MS-7673:/home/wl/桌面/c++# cat -n wait.cpp 1 #include <unistd.h> 2 #include <sys/types.h> 3 #include <sys/wait.h> 4 #include <stdio.h> 5 #include <stdlib.h> 6 #include <errno.h> 7 #include <math.h> 8 9 /* 10 * 程序入口 11 * */ 12 int main(void) 13 { 14 pid_t child; 15 16 /* 创建子进程 */ 17 if((child=fork())==-1) 18 { 19 printf("Fork Error \n" ); 20 exit(1); 21 } 22 else 23 { 24 if(child==0) // 子进程 25 { 26 printf("the child process is run\n"); 27 sleep(1); //子进程睡眠一秒,但并没有去运行父进程 28 printf("I am the child: %d\n", getpid()); 29 exit(0); 30 } 31 else //父进程 32 { 33 wait(NULL); //等到子进程退出,父进程才会运行 34 printf("the father process is run\n"); 35 printf("I am the father:%d\n",getpid()); 36 return 0; 37 } 38 } 39 } 40 41 root@wl-MS-7673:/home/wl/桌面/c++# g++ wait.cpp -o wait root@wl-MS-7673:/home/wl/桌面/c++# ./wait the child process is run I am the child: 19742 the father process is run I am the father:19741 root@wl-MS-7673:/home/wl/桌面/c++# ./wait
本例子中,父进程等待子进程结束后才执行。~
评论暂时关闭