Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/linux/22.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
execvp()和/或字符串存在问题,为什么此代码不起作用?_C_Linux_Shell_Exec_Strtok - Fatal编程技术网

execvp()和/或字符串存在问题,为什么此代码不起作用?

execvp()和/或字符串存在问题,为什么此代码不起作用?,c,linux,shell,exec,strtok,C,Linux,Shell,Exec,Strtok,我编写了以下代码,打开一个文件并执行除注释“#”之外的每一行文件: 我的文件: ls -l ls -a cat /tmp/filex 代码: 我还尝试使用run()函数编写另一个代码,它可以工作,没有问题 #include <stdio.h> #include <stdlib.h> #include <sys/stat.h> #include <fcntl.h> #include <string.h> #include <uni

我编写了以下代码,打开一个文件并执行除注释“#”之外的每一行文件:

我的文件:

ls -l
ls -a
cat /tmp/filex
代码:

我还尝试使用run()函数编写另一个代码,它可以工作,没有问题

#include <stdio.h>
#include <stdlib.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>

void run(const char *cmd, const char *arg){
    char *argv[3];
    asprintf(&argv[0],"%s", cmd);
    asprintf(&argv[1], "%s", arg);
    argv[2] = NULL;
    pid_t pid = fork();
    if(pid == 0){
        execvp(argv[0], (char * const *) argv);
        perror("error: ");
        exit(EXIT_FAILURE);
    }
    waitpid(pid, NULL, 0);
}

int main(){
    run("ls", "-l");
}
#包括
#包括
#包括
#包括
#包括
#包括
#包括
#包括
无效运行(常量字符*cmd,常量字符*arg){
char*argv[3];
asprintf(&argv[0],“%s”,cmd);
asprintf(&argv[1],“%s”,arg);
argv[2]=NULL;
pid_t pid=fork();
如果(pid==0){
execvp(argv[0],(char*const*)argv);
佩罗尔(“错误:”);
退出(退出失败);
}
waitpid(pid,NULL,0);
}
int main(){
运行(“ls”和“l”);
}
我不明白

ls: invalid option -- '
'
请参阅两个单引号。有一个新行被传递到
ls
,这确实是一个“无效选项”

getline()
返回新行,输入已被触发

在把读过的东西传给别人之前,只要把它砍掉就行了

为此,您可以使用以下方法:

line[strcspn(line, "\r\n")] = '\0';

我怀疑代码内存不足,但是
argv[0]
argv[1]
line
应该是空闲的。您是否尝试过在调试器中单步执行(非工作)程序以检查发生了什么,同时监视所有变量及其值?请花些时间来解释。注意报价的位置。你有自己不该有的地方
ls
表示选项
无效
cat
说它找不到
/tmp/filex
@ikegaminice。我认为代码不应该执行每一行;如果(cmd[0]!='#')是问题,则应
strtok_r()
返回
NULL
ls: invalid option -- '
'
line[strcspn(line, "\r\n")] = '\0';