c - C execvp 不会执行“ls -l”命令,但会执行“ls”
问题描述
#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
. 因此,如果您ls-l
在 shell 的启动脚本中创建了别名,那么这将不适用于execvp()
. 如果需要,请system()
改用。
如果您打算执行ls -l
,那么您应该执行以下操作:
const char *nargs[] = {"ls", "-l", NULL};
execvp(nargs[0], nargs);
最后,如果你真的想得到一个文件列表,你不需要调用ls
,你应该使用opendir()
+ readdir()
,或者ftw()
在 POSIX 平台上。
推荐阅读
- python - 如何使用 python-socketio 连接到“普通”websocket?
- reactjs - 如何使用 Java 中的 Selenium 测试 react-beautiful-dnd 库中的“拖放”功能?
- amazon-web-services - 目录不为空:'.elasticbeanstalk\\app_versions' Windows 10
- unix - 从 YYYYMMDD 到 DD-MON-YYYY 的日期参数格式转换
- python - 一个用于查找列表子集的最小值的衬垫
- python - 如何为 Django 路径分配默认值
- ios - 从 iOS 中查找 RaspberryPi 的本地 IP 地址
- java - 无法使用 Yocto 编译 RXTX,缺少 javac
- unity3d - 检查对象是否在屏幕外
- python - 如何利用 python 闭包编写回调函数