c - fork 和执行

标签 c linux exec fork

我正在尝试使用 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/

相关文章:

python - CC for python distutils 构建c

c++ - xcode c/c++ 链接器错误 : undefined symbol

linux - Linux 设备驱动程序开发书籍/教程/视频讲座

linux - 如何在 CMake execute_process 中使用 find -exec?

c - 如何以可以使用链接列表元素执行命令的方式解析链接列表元素

c - 无法完全执行 do-while 循环

c - scandir() 导致段错误,即使有有效的绝对路径?

c - 审查代码并评论 c linux 和网络专家

linux - 给程序相同的输入文件 100 次

sql-server-2008 - 设置@var = exec存储过程