当前位置:网站首页>Explain the wait() function and waitpid() function in C language in detail

Explain the wait() function and waitpid() function in C language in detail

2022-08-09 06:33:00 qq_36412526

C语言wait()函数:结束(中断)进程函数(常用)

#include <sys/types.h> 
#include <sys/wait.h>

pid_t wait (int * status);

函数说明:wait()会暂时停止目前进程的执行, 直到有信号来到或子进程结束. 如果在调用wait()时子进程已经结束, 则wait()会立即返回子进程结束状态值. 子进程的结束状态值会由参数status 返回, 而子进程的进程识别码也会一快返回. 如果不在意结束状态值, 则参数 status 可以设成NULL. The child to the end of the status value refer towaitpid().

返回值:如果执行成功则返回子进程识别码(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 =%d\n", 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=^d\n", 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()函数:中断(结束)进程函数(Or wait for the child to interrupt)

#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 为欲等待的子进程识别码, 其他数值意义如下:

1、pid<-1 等待进程组识别码为pid 绝对值的任何子进程.
2、pid=-1 等待任何子进程, 相当于wait().
3、pid=0 等待进程组识别码与目前进程相同的任何子进程.
4、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 中.

范例:参考wait().

注:
从本质上讲,系统调用waitpid和wait的作用是完全相同的,但waitpid多出了两个可由用户控制的参数pid和options,从而为我们编程提供了另一种更灵活的方式.

原网站

版权声明
本文为[qq_36412526]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/221/202208090628551778.html