我正在重新創建一個完整的外殼。為此,我必須模擬“|”。為此,我必須使用 dup2()、fork() 和 pipe() 函式。
我最成功的代碼是這樣的:
int exec_pipe(global *glob, char *commande)
{
int pipefd[2];
char **pipe_commandes = my_split(commande, '|');
char **left = my_str_to_word_array(pipe_commandes[0]);
char **right = my_str_to_word_array(pipe_commandes[1]);
int pid = 0;
int status;
pipe(pipefd);
pid = fork();
if (pid == 0) {
close(pipefd[1]);
dup2(pipefd[0], 0);
close(pipefd[0]);
glob->commande = right;
distribe_commande(glob);
glob->commande = NULL;
} else {
close(pipefd[0]);
dup2(pipefd[1], 1);
close(pipefd[1]);
glob->commande = left;
distribe_commande(glob);
glob->commande = NULL;
}
}
函式 distribe_commande() 導致命令的格式,以便在此函式中使用 execve() 執行它:
void exec_path_commande(char *path, global *glob)
{
int pid;
int status;
pid = fork();
if (pid == 0) {
dup2(glob->fd, glob->origine);
if (execve(path, glob->commande, glob->env) == -1)
exit(0);
} else
while (waitpid(pid, &status, 0) != -1 && !WIFEXITED(status))
error_execve(status);
}
char *path正確的格式化命令在哪里。
我的問題是,當我發送命令時ls | cat -e,命令作業:
$~> ls | cat -e
^[[0$
42sh$
build$
CMakeLists.txt$
hello$
include$
Jenkinsfile$
lib$
main.c$
Makefile$
src$
但是,如果我向程式發送另一個命令,| cat -e即使在提示符下效果仍然存在,我不明白為什么:
$~> ls | cat -e
^[[0$
42sh$
build$
CMakeLists.txt$
hello$
include$
Jenkinsfile$
lib$
main.c$
Makefile$
src$
^[[0;31m^[[1m$^[[0;36m^[[1m~^[[0;32m^[[1m> ^[[0;37m^[[0mls
^[[0$
42sh$
build$
CMakeLists.txt$
hello$
include$
Jenkinsfile$
lib$
main.c$
Makefile$
src$
^[[0;31m^[[1m$^[[0;36m^[[1m~^[[0;32m^[[1m> ^[[0;37m^[[0m
提前感謝您的回答。
uj5u.com熱心網友回復:
你dup2在錯誤的地方做事。你也有fork太多了。
重定向應該如下所示(大綱/偽代碼,不是真正的 C 代碼):
fd = open(...)
pid = fork()
if (pid == 0)
dup2(fd, 1) // redirect the output, just an example
close(fd)
exec(...)
wait(...)
注意,dup2和close位于 之后fork和 之前exec。
管道是通過管道協調的兩個(或更多)重定向,因此:
pipe(fds)
pid1 = fork()
if (pid1 == 0)
dup2(fds[0], 0)
close(fds[0])
close(fds[1])
exec(...)
pid2 = fork()
if (pid2 == 0)
dup2(fds[1], 1)
close(fds[0])
close(fds[1])
exec(...)
wait(...)
wait(...)
還要注意兩個waits 都在兩個execs 之后。如果您以其他方式(exec-wait-exec-wait)執行此操作,則類似的命令yes | head將不起作用。
所以你需要重構exec_path_commande很多。
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/471518.html
下一篇:在jqbash腳本中連接字串變數
