Chinaunix首页 | 论坛 | 博客
  • 博客访问: 542316
  • 博文数量: 150
  • 博客积分: 5010
  • 博客等级: 大校
  • 技术积分: 1861
  • 用 户 组: 普通用户
  • 注册时间: 2008-03-17 00:19
文章分类

全部博文(150)

文章存档

2011年(1)

2009年(14)

2008年(135)

我的朋友

分类: LINUX

2008-10-23 12:58:25


前些天。在一个进程中fork一个进程执行execv()去做别的,但是产生僵死进程。一直解决不了。

直到用下面的程序去fork,它的特点是产生孙子进程去执行程序。
如下


/* LAPI_Fork2() -- like fork, but the new process is immediately orphaned
 * (won't leave a zombie when it exits)
 * Returns 1 to the parent, not any meaningful pid.
 * The parent cannot wait() for the new process (it's unrelated).
 *
 * This version assumes that you *haven't* caught or ignored SIGCHLD.
 * If you have, then you should just be using fork() instead anyway.
 */


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

    if (!(pid = fork())) {
        // fork first time, in child process

        switch (fork()) {
            case 0:
                return 0;
            case -1:
                _exit( errno ); /* assumes all errnos are <256 */
            default:
                _exit(0);//孙子的父亲离开,以便让儿子的父亲回收!!
        }
    }

    // parent

    printf("LAPI_Fork2() function in Parent ");
    if (pid < 0 || waitpid(pid, &status, 0) < 0)//
儿子的父亲回收
        return -1;

    if (WIFEXITED(status)) {
        if (WEXITSTATUS(status) == 0)
            return 1;
        else
            errno = WEXITSTATUS(status);
    } else
        errno = EINTR; /* well, interrupted */

    return -1;
}


调用:

pid = LAPI_Fork2();
             TCMD_TRACE(" LAPI_Fork2()return===================================%d",pid);
             switch(pid){
              case -1:
                 TCMD_TRACE("Fork new process fails:%s\n ",strerror(errno));
                ret =-1;
                break;
             case 0:
                 TCMD_TRACE( "-----------new process--------------------%d\n",getpid());
                 TCMD_TRACE( "New process to play start up music....(unlimited loop)\n");
                 execl(AUDIO_START_MUSIC_CMD,AUDIO_START_MUSIC_CMD,START_MUSIC_CMD_PARA1,START_MUSIC_CMD_PARA2,NULL);
             }
         ret=0;
             break;

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