【发布时间】:2026-01-12 06:50:02
【问题描述】:
我试图更好地理解 exec() - 所以我在 testing.c 中有以下脚本
#include <stdio.h>
#include <sys/types.h>
#include <wait.h>
#include <unistd.h>
#include <stdlib.h>
int main(int argc, char ** argv)
{
if(argc < 2) {
fprintf(stderr,"Error:: Expecting an Argument!\n");
exit(-1);
}
pid_t pid;
pid = fork();
if (pid==0) {
execlp("./testing","testing",NULL);
fprintf(stderr, "I want to get to here...\n");
exit(-1);
}
wait(NULL);
printf("Parent and child done\n");
return 0;
}
下面的块是我用./testing one执行后的输出:
Error:: Expecting an Argument!
Parent and child done
在阅读exec() 的工作原理时,我希望在我的execlp 调用之后能够fprintf,因为它应该返回-1,我想知道我是否需要设置一个errno 或其他东西更明确地抛出一些东西以便execlp 识别错误?
【问题讨论】:
-
man 3 exec: 返回值 exec() 函数仅在发生错误时返回。返回值为 -1,设置 errno 以指示错误。 -
是什么让你认为
execlp调用失败了? -
关于:
Error:: Expecting an Argument!此消息是因为您没有提供代码所期望的命令行参数 -
贴出的代码无法编译!它缺少以下
#include语句:#include#include #include #include #include -
如果包含命令行参数,则输出为:
I want to get to here... Parent and child done
标签: c error-handling exec