我尝试了一个带有fork和execlp的程序,其中父地址空间由"ls“命令代替。
#include<stdio.h>
main()
{
int pid,j=10,fd;
pid=fork();
if(pid==0)
{
printf("\nI am the child\n");
execlp("/bin/ls","ls",NULL);
printf("\nStill I am the child\n");
}
else if (pid > 0)
{
printf("\n I am the parent\n");
wait();
}
}当我执行程序时,子代的最后一行
printf("\nStill I am the child\n");未打印。为什么?
发布于 2011-08-23 12:43:12
exec系列函数在成功时不会返回。
http://pubs.opengroup.org/onlinepubs/009604499/functions/exec.html
exec系列函数应用新的过程镜像替换当前的过程镜像。新映像应由称为新过程映像文件的常规可执行文件构建。不应从成功的exec返回,因为调用进程映像被新进程映像覆盖。如果其中一个exec函数返回到调用进程映像,则表明发生了错误;返回值应为-1,并应设置错误号以指示错误。
发布于 2011-08-23 14:52:33
exec函数不仅仅是执行您的命令。它们实际上会用您选择的可执行文件(在本例中为/bin/ls)替换流程的执行上下文。
换句话说,由于ls函数以终止其进程(例如'exit‘或返回主函数等)结束,因此您的子进程将在ls的执行结束时被终止。
实际上,您可以使用这个printf调用来打印一些错误,例如:
if(pid==0)
{
printf("\nI am the child\n");
execlp("/bin/ls","ls",NULL);
printf("\nError: Could not execute function %s\n", "/bin/ls");
_exit(0); //make sure you kill your process, it won't disappear by itself.
}发布于 2013-08-27 13:15:58
原因很简单: exec()函数只在发生错误时返回。有关相同信息,请参阅exec()函数的手册页。
当exec()函数被调用时,到底发生了什么:
execl()不会创建新的进程-它会修改VADS和相关内容-此外,还会修改执行上下文。
不再使用
中新程序的(),用新的hw上下文覆盖了main
- execution context and code/data/heap/stack of old application in the child process are completely destroyed - no longer available.
- only time execve() or execl() will return to the same application/code of the current process is when execve() or execl() fails to load a new application in the current process - meaning, the only time execv()/execvl() or family of calls will return is when there is error in completing execv()/execl()/family of calls.
注意:您必须验证exec()系列系统调用API的返回值是否存在错误/错误代码-根据错误/错误代码,您可以终止当前进程或采取其他操作。
https://stackoverflow.com/questions/7156338
复制相似问题