gpt4 book ai didi

c - 为什么我的 cd 命令不起作用?

转载 作者:行者123 更新时间:2023-11-30 19:56:24 24 4
gpt4 key购买 nike

我正在尝试用 C 语言实现 cd 命令。它应该这么简单

printf("change directory to %s\n" , argv[2]);
chdir(argv[2]);

为什么它对我不起作用?代码位于一个完整的程序中,它还执行其他一些操作。如果需要的话,我可以创建一个最小的例子。

    $ cc digenv.c
developer@developer-VirtualBox:~/Desktop/kth/os/smallshell/oslab$ ./a.out cd test
change directory to test
developer@developer-VirtualBox:~/Desktop/kth/os/smallshell/oslab$ pwd
/home/developer/Desktop/kth/os/smallshell/oslab
developer@developer-VirtualBox:~/Desktop/kth/os/smallshell/oslab$ ls test
developer@developer-VirtualBox:~/Desktop/kth/os/smallshell/oslab$

#include <sys/types.h>
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
struct command
{
const char **argv;
};
/* Helper function that spawns processes */
int spawn_proc (int in, int out, struct command *cmd) {
pid_t pid;
if ((pid = fork ()) == 0) {
if (in != 0) {
dup2 (in, 0);
close (in);
}
if (out != 1) {
dup2 (out, 1);
close (out);
}
return execvp (cmd->argv [0], (char * const *)cmd->argv);
}
return pid;
}
/* Helper function that forks pipes */
int fork_pipes (int n, struct command *cmd) {
int i;
int in, fd [2];
in = 0;
for (i = 0; i < n - 1; ++i) {
pipe (fd);
spawn_proc (in, fd [1], cmd + i);
close (fd [1]);
in = fd [0];
}
if (in != 0)
dup2 (in, 0);
return execvp (cmd [i].argv [0], (char * const *)cmd [i].argv);
}

int main (int argc, char ** argv) {
int i;
if (argc == 1) { /* There were no arguments */
const char *printenv[] = { "printenv", 0};
const char *sort[] = { "sort", 0 };
const char *less[] = { "less", 0 };
struct command cmd [] = { {printenv}, {sort}, {less} };
return fork_pipes (3, cmd);
}
if (argc > 1) { /* I'd like an argument */

if (strncmp(argv[1], "cd", 2)) {
char *tmp;
int len = 1;
for( i=1; i<argc; i++)
{
len += strlen(argv[i]) + 2;
}
tmp = (char*) malloc(len);
tmp[0] = '\0';
int pos = 0;
for( i=1; i<argc; i++)
{
pos += sprintf(tmp+pos, "%s%s", (i==1?"":"|"), argv[i]);
}
const char *printenv[] = { "printenv", 0};
const char *grep[] = { "grep", "-E", tmp, NULL};
const char *sort[] = { "sort", 0 };
const char *less[] = { "less", 0 };
struct command cmd [] = { {printenv}, {grep}, {sort}, {less} };
return fork_pipes (4, cmd);
free(tmp);
} else { /* change directory */
printf("change directory to %s\n" , argv[2]);
chdir(argv[2]);
}
}
exit(0);
}

最佳答案

根据其 documentation

The chdir() function only affects the working directory of the current process.

所以你不能改变父进程的目录。

关于c - 为什么我的 cd 命令不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29462752/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com