码迷,mamicode.com
首页 > 其他好文 > 详细

UNIX环境高级编程8.10exec函数

时间:2015-02-06 16:30:55      阅读:131      评论:0      收藏:0      [点我收藏+]

标签:

 

技术分享

 

技术分享

 

技术分享

技术分享

 

技术分享

 

技术分享

// proc/exec1.c 8-8
#include "apue.h"
#include <sys/wait.h>

const char* env_init[] = { "USER=unknown", "PATH=/home/sunyj/apue/proc/", NULL };

int main(void)
{
    pid_t pid;

    if ((pid = fork()) < 0)
    {
        err_sys("fork error");
    }
    else if (pid == 0)
    {   /* specify pathname, specify environment */
        if (execle("/home/sunyj/apue/proc/echoall", "echoall", "myarg1",
                    "MY ARG2", (char *)0, env_init) < 0)
        {
            err_sys("execle error");
        }
    }

    if (waitpid(pid, NULL, 0) < 0)
    {
        err_sys("wait error");
    }

    if ((pid = fork()) < 0)
    {
        err_sys("fork error");
    }
    else if (pid == 0)
    {   /* specify filename, inherit environment */
        if (execlp("echoall", "echoall", "only 1 arg", (char *)0) < 0)
        {
            err_sys("execlp error");
        }
    }

    return 0;
}

 

技术分享

 

// proc/echoall.c 8-9
#include "apue.h"

int main(int argc, char *argv[])
{
    int			i;
    char		**ptr;
    extern char	**environ;

    for (i = 0; i < argc; i++)		/* echo all command-line args */
    {
        printf("argv[%d]: %s\n", i, argv[i]);
    }

    for (ptr = environ; *ptr != 0; ptr++)	/* and all env strings */
    {
        printf("%s\n", *ptr);
    }

    return 0;
}

 

我测试的结果是,execle可以正确执行,execlp报找不到echoall的错误,除非,我将echoall的路径在shell中加入环境变量PATH中,我不清楚是为什么。

 

技术分享

UNIX环境高级编程8.10exec函数

标签:

原文地址:http://www.cnblogs.com/sunyongjie1984/p/4277407.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!