详解C语言中的wait()函数和waitpid()函数
C语言wait()函数:结束(中断)进程函数(常用) #include <sys/types.h> #include <sys/wait.h> 定义函数: pid_t wait (int * status); 函数说明:wait()会暂时停止目前进程的执行,直到有信号来到或子进程结束. 如果在调用wait()时子进程已经结束,则wait()会立即返回子进程结束状态值. 子进程的结束状态值会由参数status 返回,而子进程的进程识别码也会一快返回. 如果不在意结束状态值,则参数 status 可以设成NULL. 子进程的结束状态值请参考waitpid(). 返回值:如果执行成功则返回子进程识别码(PID),如果有错误发生则返回-1. 失败原因存于errno 中. 范例 #include <stdlib.h> #include <unistd.h> #include <sys/types.h> #include <sys/wait.h> main() { pid_t pid; int status,i; if(fork() == 0) { printf("This is the child process. pid =%dn",getpid()); exit(5); } else { sleep(1); printf("This is the parent process,wait for child...n"; pid = wait(&status); i = WEXITSTATUS(status); printf("child's pid =%d . exit status=^dn",pid,i); } } 执行: This is the child process. pid=1501 This is the parent process,wait for child... child's pid =1501,exit status =5 C语言waitpid()函数:中断(结束)进程函数(或等待子进程中断) #include <sys/types.h> #include <sys/wait.h> 定义函数: pid_t waitpid(pid_t pid,int * status,int options); 函数说明:waitpid()会暂时停止目前进程的执行,则参数status 可以设成NULL. 参数pid 为欲等待的子进程识别码,其他数值意义如下: 1、pid<-1 等待进程组识别码为pid 绝对值的任何子进程. 参数option 可以为0 或下面的OR 组合: WNOHANG:如果没有任何已经结束的子进程则马上返回,不予以等待. 返回值:如果执行成功则返回子进程识别码(PID),如果有错误发生则返回-1. 失败原因存于errno 中. 范例:参考wait(). (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |