gpt4 book ai didi

C execvp 不会执行 "ls -l"命令但会执行 "ls"

转载 作者:太空宇宙 更新时间:2023-11-04 02:20:52 25 4
gpt4 key购买 nike

#include <stddef.h>
#include <string.h>
#include <stdio.h>
#include <signal.h>
#include <unistd.h>
int flag;
void catch (int sig)
{

if (sig == SIGINT){
flag = 1;
}

if (sig == SIGHUP){
flag == 2;
}
}



int main ()
{
int i;
char *nargs[40];
nargs[0] = "ls-l";
signal(SIGINT, catch);
signal(SIGHUP, catch);
i = 2;
while(i == 2){
if (flag == 1){
execvp(nargs[0],nargs);
}
if (flag ==2){
execvp(nargs[1],nargs);
}

}
return 0;
}

这里当 nargs[0] 设置为 "ls-l"或 "ls -l"时它不会在 SIGINT 上执行命令,但是当 nargs[0] 设置为 "ls"时它只会执行命令美好的。我究竟做错了什么? while 循环条件只是它会永远循环的方式。

最佳答案

execvp() 不会启动 shell,它会尝试查找您直接在 $PATH 中指定的二进制文件。因此,如果您在 shell 的启动脚本中创建了一个别名 ls-l,那么这将不适用于 execvp()。如果需要,请改用 system()

如果你打算执行 ls -l,那么你应该这样做:

const char *nargs[] = {"ls", "-l", NULL};
execvp(nargs[0], nargs);

最后,如果你真的想得到一个文件列表,你不需要调用ls,你应该使用opendir()+readdir (),或者 POSIX 平台上的 ftw()

关于C execvp 不会执行 "ls -l"命令但会执行 "ls",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58335253/

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