我正在尝试使用 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();
}
}
当我执行程序时最后一行child
printf("\nStill I am the child\n");
未打印。为什么?
最佳答案
exec
系列函数在成功时不返回。
http://pubs.opengroup.org/onlinepubs/009604499/functions/exec.html
The exec family of functions shall replace the current process image with a new process image. The new image shall be constructed from a regular, executable file called the new process image file. There shall be no return from a successful exec, because the calling process image is overlaid by the new process image.
If one of the exec functions returns to the calling process image, an error has occurred; the return value shall be -1, and errno shall be set to indicate the error.
关于c - fork 和执行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7156338/