gpt4 book ai didi

c - 使用 C-if 条件实现 cd 系统调用

转载 作者:太空狗 更新时间:2023-10-29 16:54:00 25 4
gpt4 key购买 nike

这是使用 C 实现 cd 系统调用的代码。此代码的问题是它没有进入 if 条件 if(strcmp(buffer,"cd") == 0)我不明白为什么。

#include<sys/stat.h>
#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include<dirent.h>
#include<error.h>

#define BUFFERSIZE 20
int main(){

char *args[80];
char buffer[BUFFERSIZE];
char *prompt = "OS";
char *a = ">";
printf("%s%s",prompt,a);
fgets(buffer, BUFFERSIZE, stdin);

char *tok;
tok = strtok (buffer," ");


while(buffer != NULL){
buffer[strlen(buffer)-1] = '\0';
pid_t pid;
pid = fork();
if(pid < 0){
fprintf(stderr, "Fork failed");
return 1;
}
else if(pid == 0){

if(strcmp(buffer,"cd") == 0){
tok = strtok(NULL,"\n");
cd(tok);
}
printf("%s%s",prompt,a);
fgets(buffer, BUFFERSIZE, stdin);
}
else{
wait(NULL);
}
}
return 0;
}


int cd(char *pth){
char path[1000];
strcpy(path,pth);

static char *prompt = "OS";
static char *a = ">";
char *token;

char cwd[256];
getcwd(cwd,sizeof(cwd));

strcat(cwd,"/");
strcat(cwd,path);
chdir(cwd);

printf("%s-%s%s",prompt,path,a);
return 0;
}

最佳答案

根据其他人的建议更新了逻辑。

这里不需要子进程。如果你想要多任务处理,那么使用线程。 在后台运行的进程可能需要子进程。

以下程序对我有用:

#include <stdio.h>

#include <sys/stat.h>
#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <dirent.h>
//#include <error.h>

int hasPrefix(char const *, char const *);
int cd(char *pth);

#define BUFFERSIZE 200
int main(){

char buffer[BUFFERSIZE];
char *prompt = "OS";
char *a = ">";

char *tok;
tok = strtok (buffer," ");


while(buffer != NULL){
bzero(buffer, BUFFERSIZE);
printf("%s%s",prompt,a);
fgets(buffer, BUFFERSIZE, stdin);
if(hasPrefix(buffer,"cd") == 0){
tok = strchr(buffer,' '); //use something more powerful
if(tok) {
char *tempTok = tok + 1;
tok = tempTok;
char *locationOfNewLine = strchr(tok, '\n');
if(locationOfNewLine) {
*locationOfNewLine = '\0';
}
cd(tok);
}
}else{
system("ls"); //for testing the CWD/PWD
}
}
return 0;
}

int hasPrefix(char const *p, char const *q)
{
int i = 0;
for(i = 0;q[i];i++)
{
if(p[i] != q[i])
return -1;
}
return 0;
}

int cd(char *pth){
char path[BUFFERSIZE];
strcpy(path,pth);

char cwd[BUFFERSIZE];
if(pth[0] != '/')
{// true for the dir in cwd
getcwd(cwd,sizeof(cwd));
strcat(cwd,"/");
strcat(cwd,path);
chdir(cwd);
}else{//true for dir w.r.t. /
chdir(pth);
}

return 0;
}

关于c - 使用 C-if 条件实现 cd 系统调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16094814/

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