gpt4 book ai didi

c - dup2 导致程序停止

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

int shell (int argc, char *argv[]) {
char *s = malloc(INPUT_STRING_SIZE+1); /* user input string */
tok_t *t; /* tokens parsed from input */
int lineNum = 0;
int fundex = -1;
pid_t pid = getpid(); /* get current processes PID */
pid_t ppid = getppid(); /* get parents PID */
pid_t cpid, tcpid, cpgid;

init_shell();

printf("%s running as PID %d under %d\n",argv[0],pid,ppid);

lineNum=0;

const int BUF_SIZE = 200;
char buf[BUF_SIZE];
getcwd(buf, BUF_SIZE);

fprintf(stdout, "%d %s: ", lineNum++, buf);
while ((s = freadln(stdin))){
char *ptrA, *ptrB;
ptrA = strstr(s, "<");
ptrB = strstr(s, ">");
if (ptrA) {
*ptrA = '\0';
ptrA++;
}
if (ptrB) {
*ptrB = '\0';
ptrB++;
}
if (ptrA && ptrB) {

} else if (ptrA) {

} else if (ptrB) {
size_t ln = strlen(ptrB) - 1;
if (ptrB[ln] == '\n') // get rid of the trailing newline
ptrB[ln] = '\0';
int newfd; /* new file descriptor */
if ((newfd = open(ptrB, O_CREAT|O_TRUNC|O_WRONLY, S_IRUSR|S_IWUSR|S_IXUSR)) < 0) {
perror("Can't open outfile file\n"); /* open failed */
exit(1);
}
printf("newfd: %d\n", newfd);
dup2(newfd, 1);
printf("Here\n");
}
printf("%s\n", s);
t = getToks(s); /* break the line into tokens */
fundex = lookup(t[0]); /* Is first token a shell literal */
if(fundex >= 0) {
cmd_table[fundex].fun(&t[1]);
} else {
char *bin;
if (get_binary(t[0], &bin) == 0) {
t[0] = bin;
}
pid_t child_pid = fork();
int exit_code;
if (child_pid == 0) {
execv(t[0], &t[0]);
} else {
wait(&exit_code);
}
}
getcwd(buf, BUF_SIZE);
fprintf(stdout, "%d %s: ", lineNum++, buf);
}
return 0;
}

我使用 wc shell.c>test 测试我的 shell,结果是我在终端上看到一个空行,就好像它在等待我的输入一样。当我按 Enter 键时,出现段错误。如果我注释掉 dup2 行,shell 就可以正常工作(当然,但没有重定向)。我在 Windows 上使用 Cygwin,如果有帮助的话。

最佳答案

我把我的副本放在了错误的地方。我需要在 fork 之后、执行之前复制。

关于c - dup2 导致程序停止,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28378700/

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