您的位置:首页 > 编程语言

UNIX环境高级编程8.10exec函数

2015-02-06 16:05 351 查看












// 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中,我不清楚是为什么。



内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: