UNIX环境高级编程8.10exec函数

6W8UE$U`({5PZ33PAFKDJ76

 

YK$R{}F[$%6]680T%B65SBP

 

6DKKDVLRQXNTJ`WT_B)OBVI

_5VE{1`_G63Z9MZ9RTF@ZOW

 

(}FK}`NW]]0XVJI~RPBR%SB

 

$~EP52]N~[3MMK`]YHYZ[~W

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

PX@8YE]G1`F)OT_D2IBG7AY

// 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
", i, argv[i]);
    }

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

    return 0;
}

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

7fe0ac6eaf14af9dafaf10cc1f9bb130

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