Chinaunix首页 | 论坛 | 博客
  • 博客访问: 830018
  • 博文数量: 213
  • 博客积分: 5048
  • 博客等级: 大校
  • 技术积分: 1883
  • 用 户 组: 普通用户
  • 注册时间: 2008-04-14 10:14
文章分类

全部博文(213)

文章存档

2011年(4)

2010年(55)

2009年(47)

2008年(107)

我的朋友

分类: LINUX

2008-10-28 16:13:07

本文主要参考《unix环境高级编程》
 
当一个进程正常或异常终止时,内核就向其父进程发送SIGCHLD信号。
如果进程由于接收到SIGCHLD信号而调用wait,则可期望wait会立即返回。但是如果在一个任一时刻调用wait,则进程可能会阻塞。

#include <sys/types.h>
#include <sys/wait.h>
pid_t wait(int *statloc) ;
pid_t waitpid(pid_pt i d , int *statloc, int options) ;

这两个函数的区别是:
• 在一个子进程终止前, wait 使其调用者阻塞,而waitpid 有一选择项,可使调用者不阻
塞。
• waitpid并不等待第一个终止的子进程—它有若干个选择项,可以控制它所等待的进程。

 

 宏 说明
 WIFEXITED(status)  若为正常终止子进程返回的状态,则为真。对于这种情况可执行WEXITSTATUS(status)取子进程传送给e x i t或_ e x i t参数的低8位
 WIFSIGNALED(status)  若为异常终止子进程返回的状态,则为真(接到一个不捕捉的信号)。对于
这种情况,可执行
W T E R M S I G(s t a t u s)
取使子进程终止的信号编号。
 WIFSTOPPED(status)  若为当前暂停子进程的返回的状态,则为真。对于这种情况,可执行
W S T O P S I G(s t a t u s)
取使子进程暂停的信号编号

下面先举例说明用wait函数演示不同的exit值,代码分成两个c文件,一个是main.c

还有一个是pr_exit.c函数,这个是使用上面的宏处理进程终止状态。

代码如下:

/*
 *main.c
*/

#include "apue.h"
#include <sys/wait.h>

int
main (void)
{
    pid_t pid;
    int status;

    if ((pid = fork()) < 0)
        err_sys("fork error");
    else if (pid == 0)
        exit(7);
        
    if (wait(&status) != pid)
        err_sys("wait error");
    pr_exit(status);
    
    if ((pid = fork()) < 0)
        err_sys("fork error");
    else if (pid == 0)
        abort();
        
    if (wait(&status) != pid)
        err_sys("wait error");
    pr_exit(status);

    if ((pid = fork()) < 0)
        err_sys("fork error");
    else if (pid == 0)
        status /= 0;
        
    if (wait(&status) != pid)
        err_sys("wait error");
    pr_exit(status);


/*
 * pr_exit.c
 */

#include "apue.h"
#include <sys/wait.h>

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));
    }

}

如果把fork函数和前面父子进程之间关系了解的话,这部分代码还是很容易懂得,main.c中测试了三种情况,一是正常exit,二是调用 abort,三是让子进程除0。恩是比较简单,没什么好说的。不过pr_exit.c中有一个ifdef的用法比较特别哦,呵呵,像我这样菜鸟可以学习一下。

想练习一下makefile写了一个简单的不能在简单的wait.mk,呵呵完全是没事找事做。

 

wait:main.o pr_exit.o
   gcc $^ -o $@ libapue.a
main.o:main.c apue.h
   gcc -c $< 
pr_exit.o:pr_exit.c apue.h
   gcc -c $< 
clean:
   rm -f *.o

阅读(1711) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~