gpt4 book ai didi

c - 管道实现中的错误,我面临这个错误,ls : write error: Bad file descriptor

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

我在c中实现shell时做了这个,但是尽管在实现管道时,我遇到了这个错误ls:write error:Bad file detector,而且我不明白为什么会出现这个错误,请帮忙。

#include<stdio.h>
#include<unistd.h>
#include <stdlib.h>
void execute(char **argv)
{
pid_t pid;
int status;
//fflush(0);
pid_t id ;
int out=0,in=0,pip=0;
int fds[2];

if ((pid = fork()) < 0) { /* fork a child process */
printf("*** ERROR: forking child process failed\n");
exit(1);
}
if (pid==0) {
close(1); /* close normal stdout */
dup2(fds[1],1); /* make stdout same as pfds[1] */
close(fds[0]); /* we don't need this */
execlp(argv[0],argv[0],argv[1],NULL);
}
else {
close(0); /* close normal stdin */
dup2(fds[0],0); /* make stdin same as pfds[0] */
close(fds[1]); /* we don't need this */
execlp(argv[3],argv[3],argv[4], NULL);
}


}

最佳答案

在调用 fork() 之前,您似乎错过了对 pipe(fds); 的调用。您还缺少一些 close() 调用。如果将管道的一端(使用 dup()dup2())复制到标准输入或标准输出,则应关闭两者来自 pipe() 的原始描述符。

还有一个强有力的论点是您应该检查系统调用的返回值。您可以使用这样的函数:

#include <stdarg.h>
#include <stdio.h>
#include <string.h>
#include <errno.h>
#include <stdlib.h>

extern void err_exit(const char *fmt, ...);

void err_exit(const char *fmt, ...)
{
int errnum = errno;
va_list args;
va_start(args, fmt);
vfprintf(stderr, fmt, args);
va_end(args);
if (errnum != 0)
fprintf(stderr, " (%d: %s)", errnum, strerror(errnum));
fputc('\n', stderr);
exit(1);
}

您可以像这样使用它:

if (dup2(fds[2], 1) != 0)
err_exit("dup2(%d, %d) failed", fds[2], 1);

关于c - 管道实现中的错误,我面临这个错误,ls : write error: Bad file descriptor,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13428267/

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