简体   繁体   English

C执行管道:execlp工作,而execvp没有

[英]C executing a pipe: execlp works while execvp doesn't

Could someone explain to me why this gives the normal behavior (ls | cat) 有人可以向我解释为什么这会给出正常的行为(ls | cat)

int fd[2]; pipe(fd);
pid_t pid = fork();
if(pid > 0) {
    close(fd[0]);
    close(STDOUT_FILENO);
    dup2(fd[1],STDOUT_FILENO);
    execlp("ls","ls",NULL);
} else if (pid == 0) {
    close(fd[1]);
    close(STDIN_FILENO);
    dup2(fd[0],STDIN_FILENO);
    execlp("cat","cat",NULL);
} else {
    error(1, errno, "forking error");
}

but when I change execlp to execvp suddenly nothing is output and exit status is 255? 但是当我将execlp更改为execvp时突然没有输出任何内容并退出状态为255? Code: 码:

int fd[2]; pipe(fd);
pid_t pid = fork();
if(pid > 0) {
    close(fd[0]);
    close(STDOUT_FILENO);
    dup2(fd[1],STDOUT_FILENO);
    char **args = {"ls", NULL};
    execvp("ls",args);
} else if (pid == 0) {
    close(fd[1]);
    close(STDIN_FILENO);
    dup2(fd[0],STDIN_FILENO);
    char **args = {"cat", NULL};
    execvp("cat",args);
} else {
    error(1, errno, "forking error");
}

I'd really like to use execvp because I'll be executing commands with variable length arg lists. 我真的很想使用execvp因为我将执行带有可变长度arg列表的命令。 Help would be much appreciated. 非常感谢帮助。

char **args = {"ls", NULL}; should be char *args[] = {"ls", NULL}; 应该是char *args[] = {"ls", NULL}; , and the same for the second args (for cat ). 和第二个args (对于cat )相同。

(It's too late here, so I can't think of the reason for the first one to compile . At least it gives a warning). (现在为时已晚,所以我无法想到第一个编译的原因。至少它会发出警告)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM