gpt4 book ai didi

即使可执行文件存在,C `execlp`也会失败

转载 作者:行者123 更新时间:2023-11-30 18:41:35 27 4
gpt4 key购买 nike

我是 C 语言新手。我正在通过 Stevens & Rago 的书学习 UNIX。我有一个问题。早期的数字之一在我的实现中不起作用。

#include "apue.h"                                     
#include <sys/wait.h>

int
main(void)
{
char buf[MAXLINE];
pid_t pid;
int status;

printf("%% ");
while (fgets(buf, MAXLINE, stdin) != NULL) {
if (buf[strlen(buf) - 1] == "\n")
buf[strlen(buf) - 1] = 0;

if ((pid = fork()) < 0) {
err_sys("Fork error: %d");
}
else if ((pid == 0) && (access(buf, F_OK ) != 1)){ /* Here I have an extra check to ensure, that the binary exists. */
execlp(buf, buf, (char *)0);
err_ret("Couldn't execute: %s", buf);
exit(127);
}

if ((pid = waitpid(pid, &status, 0)) < 0)
err_sys("waitpid error");
printf("%% ");
}
exit(0);
}

当我启动程序时:

$ ./exec
% /bin/ls
Couldn't execute: /bin/ls
: No such file or directory

我有几个关于 execlp(buf, buf, (char *)0); 的问题:

为什么execlp无法执行二进制文件?

int execlp(const char *file, const char *arg, ...);

为什么buf传递了两次?如果第二个参数必须是二进制参数。我找不到,它是什么意思:(char *)0?这是什么指针?那里的零是什么?

最佳答案

Couldn't execute: /bin/ls
: No such file or directory

请注意,错误消息位于新行中,但您尝试从输入中删除行尾字符。所以您的删除似乎不起作用。

原因是:

if (buf[strlen(buf) - 1] == "\n")

您正在将字符 (buf[x]) 与字符串 ("\n")(即指针)进行比较。打开编译器的警告并仔细阅读它们。

试试这个:

if (buf[strlen(buf) - 1] == '\n')

execlp 的参数在 its man page 中描述。 :

The first argument, by convention, should point to the filename associated with the file being executed.

或者在 POSIX 中 here

(char *)0char* 类型的空指针。这里没有发生什么神奇的事情,值为 0 的整型常量是一个空指针常量。但由于 execlp 是一个可变参数函数,因此强制转换是必要的 - 否则常量零将被视为 int ,它可能与指针的大小不同(并且空指针的内部表示可能与整数 0 的内部表示不同,从而导致未定义的行为。

关于即使可执行文件存在,C `execlp`也会失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20826120/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com