c - 为什么这不删除用户命令末尾的“&”?
问题描述
我正在用 C 编写一个基本的 shell,如果输入的命令包含 &,那么它将在后台运行并且用户仍然可以执行其他命令。
但由于某种原因,我可以让程序在后台运行,所以我知道 IF 语句有效(它检查'&')但我不能让它从命令。
以下是相关代码,欢迎提问:
int main(void)
{
Command cmd;
int n;
while (!done) {
char *line;
line = readline("> ");
//This should check if 'line' contains an &, and remove it if so.
if (strchr(line, "&") != NULL) {
line[strlen(line) - 1] = '\0';
char **cmds;
cmds = separateCmd(line);
if (!line) {
/* Encountered EOF at top level */
done = 1;
} else {
stripwhite(line);
if(*line) {
add_history(line);
/* execute it */
n = parse(line, &cmd);
PrintCommand(n, &cmd);
executeBgCmd(cmds);
}
}
if(line) {
free(line);
}
} else {
char **cmds;
cmds = separateCmd(line);
if (!line) {
/* Encountered EOF at top level */
done = 1;
} else {
stripwhite(line);
if(*line) {
add_history(line);
/* execute it */
n = parse(line, &cmd);
PrintCommand(n, &cmd);
executeCmd(cmds);
}
}
if(line) {
free(line);
}
}
}
return 0;
}
任何帮助将非常感激。提前谢谢你:D
解决方案
当我编译您的代码并查看我看到的警告时:
warning: passing argument 2 of ‘strchr’ makes integer from pointer without a cast [-Wint-conversion]
所以编译器告诉我你的代码是错误的!查找strchr
(例如http://man7.org/linux/man-pages/man3/strchr.3.html),我看到strchr
期望第二个参数是要搜索的字符。但是您的代码传递了一个字符串(或更准确地说:指向字符串第一个字符的指针):
if (strchr(line, "&") != NULL) {
^^^
ups
试试这个
if (strchr(line, '&') != NULL) {
从手册页中,我还可以看到strchr
如果找到它,它会返回一个指向该字符的指针。因此,编写如下代码可能是有意义的:
char* pHit = strchr(line, '&');
if (pHit != NULL) {
*pHit = '\0'; // Terminate string at first &
}
所以&
不必是最后一个字符。
一个简单的测试程序可以是:
int main()
{
char line[] = "hello & world";
printf("Before: %s\n", line);
char* pHit = strchr(line, '&');
if (pHit != NULL) {
*pHit = '\0';
}
printf("After: %s\n", line);
return 0;
}
输出:
Before: hello & world
After: hello
推荐阅读
- c# - 未捕获异步代码中的实体框架异常
- python-3.x - 如何动态修改函数的签名
- python - 如何在python中绘制随机半圆,相同大小但不同方向?
- vue.js - 在 v-card 中的 v-img 内添加浮动按钮
- python - 通过 pip 在 raspberry pi 3 (Jessie) 中安装 google-cloud-speech python API 时出现问题
- android - 如何在 Heremaps API (Android) 上添加 MapOverlay 到地图时禁用蓝色图钉
- c++ - 为什么我得到 realloc() 无效的旧大小?
- html - text-decoration:none 不会删除链接下划线,但 line-through 工作正常,为什么?
- html - 使导航栏拆分但响应式
- vb.net - 如何修复尝试以编程方式创建打印机端口的未指定错误?