gpt4 book ai didi

linux - 把猫放在后台​​卡住我的 shell

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:51:41 24 4
gpt4 key购买 nike

简介用户体验作为类(class)作业的一部分,我正在用 Linux 编写自己的 shell。我在将某些进程置于后台时遇到问题。我知道在命令末尾放置一个“&”可以使进程在后台运行,父进程(myShell)不必等待它。它与 ls -l &、firefox & 等一起工作正常,

问题

我真正关心的问题是 cat &。在这里,当我运行此命令时,cat 进程进入后台并返回 myShell(parent proc) 提示符,尽管我可以键入但 myshell 在几秒钟内被卡住。

这与阻塞输入等有什么关系吗,有什么建议吗?谢谢。

编辑:这是我的代码中的一个函数,它按照@minitech 的要求执行我的 shell 给出的命令

void executeCmd(char **cmdArgs, int inRedirectFd, int outRedirectFd, char *inFileName, char *outFileName, int bgProc, int inPipe, int outPipe, int *pipeFd1, int *pipeFd2){
int childPid;
childPid = fork();

if(childPid==0){

//writing the pipes before the redirection because the redirection can overwrite pipes
if(!inPipe && outPipe){
close(pipeFd1[0]);
dup2(pipeFd1[1], STDOUT_FILENO);
}
else if(inPipe && !outPipe){
close(pipeFd1[1]);
dup2(pipeFd1[0], STDIN_FILENO);
}
else if(inPipe && outPipe){
close(pipeFd1[1]);
close(pipeFd2[0]);
dup2(pipeFd1[0], STDIN_FILENO);
dup2(pipeFd2[1], STDOUT_FILENO);
}

if(outRedirectFd==1){
//token = strtok(NULL, " ");
int fd = open(outFileName, O_WRONLY | O_APPEND | O_CREAT, S_IRUSR | S_IWUSR | S_IROTH | S_IRGRP);
if(fd==-1){
printf("myShell: %s: %s\n", cmdArgs[0], strerror(errno));
}
dup2(fd, STDOUT_FILENO);
}
if(inRedirectFd==0){
//token = strtok(NULL," ");
int fd = open(inFileName, O_RDONLY | O_APPEND, S_IRUSR | S_IWUSR | S_IROTH | S_IRGRP);
if(fd == -1){
printf("myShell: %s: %s\n", cmdArgs[0], strerror(errno));
}
dup2(fd, STDIN_FILENO);
}

execvp(cmdArgs[0], cmdArgs);
printf("myShell: %s: %s\n", cmdArgs[0], strerror(errno));
_Exit(EXIT_FAILURE);
}
else{
if(!bgProc){
int retStatus;
waitpid(childPid, &retStatus, 0);
//waitpid(childPid, &retStatus, 0);
//printf("%d\n", retStatus);
}
else{
//printf("parentDesn't Wait");
}
}

抛出你能想到的任何其他建议。谢谢。

最佳答案

cat 在没有文件参数的情况下被调用时,它处理 stdin。当您使用 cat & 时,它会进入后台并等待来自 stdin 的输入。由于您没有提供一种方法来指示 stdin 结束,因此它会一直等待。

如果您向 cat 提供文件,如 cat test.txt &,它不会卡住您的 shell。

关于linux - 把猫放在后台​​卡住我的 shell ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32984469/

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