execl 错误:没有这样的文件或目录

Error at execl: No such file or directory

这是我们的教授给我们的execl()的例子。一个文件夹里有2个文件,com1.c看起来像

#include <stdio.h>
#include <unistd.h>

int main(){
    printf("hello...");
    fflush(stdout);
    execlp("com2","com2",(char*)NULL);
    perror("err at execl");
    return 1;
}

和com2.c看起来像

#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>

int main(){
    write(1, "...you unicorn ;)",13);
    return 0;
}

在运行时它给了我这条信息: hello...err at execl: No such file or directory

我怎样才能得到“你好......你独角兽;” ? 期待感谢。

确保包含 com2 的目录在您的 PATH 环境变量中。

PATH=$PATH:/path/to/directory

其中 /path/to/directory 是您放置 com2.

的目录

您还没有指定 OS 您是什么 运行 ...但是,一般来说,包含您希望执行的程序的目录应该在您的 $PATH:

https://linux.die.net/man/3/execlp

The execlp(), execvp(), and execvpe() functions duplicate the actions of the shell in searching for an executable file if the specified filename does not contain a slash (/) character. The file is sought in the colon-separated list of directory pathnames specified in the PATH environment variable.

If this variable isn't defined, the path list defaults to the current directory followed by the list of directories returned by confstr(_CS_PATH). (This confstr(3) call typically returns the value "/bin:/usr/bin".) If the specified filename includes a slash character, then PATH is ignored, and the file at the specified pathname is executed.

注:

On some other systems, the default path (used when the environment does not contain the variable PATH) has the current working directory listed after /bin and /usr/bin, as an anti-Trojan-horse measure. Linux uses here the traditional "current directory first" default path.