gpt4 book ai didi

c - 伪终端不打印输出

转载 作者:太空宇宙 更新时间:2023-11-04 03:21:15 25 4
gpt4 key购买 nike

下面是我的代码,旨在打开一个额外的 gnome 终端并在新打开的终端控制台中打印前 20 个斐波那契数:

#include <stdio.h>
#include "apue.h"

int Fibonacci(unsigned int n);

int main() {
char cmd[256];
char str[40][256];
char *name = tempnam(NULL, NULL);
char *line = "\n";
FILE *log;

mkfifo(name, 0777);
log = fopen(name, "w+");

for (unsigned int i = 0; i < 20; i++) {
sprintf(str[(2 * i)], "%s",line);
fputs(str[(2 * i)], log);
sprintf(str[(2 * i) + 1], "%u\n", Fibonacci(i));
fputs(str[(2 * i) + 1], log);
fflush(NULL);
}
if (fork() == 0) {
sprintf(cmd, "gnome-terminal -e cat %s", name);
system(cmd);
for (unsigned int j = 0; j < 40 ; j++) {
fgets(str[j], sizeof(cmd), log);
}
exit(0);
} else
if (fork() < 0) {
perror("fork () error");
}
}

int Fibonacci(unsigned int n) {
if (n == 0) {
return 0;
} else
if (n == 1) {
return 1;
} else
if (n > 1) {
return Fibonacci(n - 2) + Fibonacci(n - 1);
}
}

当我编译它时,我收到以下警告消息:

-*- mode: compilation; default-directory: "/usr/lib/gcc/x86_64-linux-gnu/4.8.4/include/" -*-
Compilation started at Sun Sep 3 15:46:28

gcc -o FIB0 Fibonacci.c
/tmp/ccobnJV9.o: In function `main':
Fibonacci.c:(.text+0x231f): warning: the use of `tempnam' is dangerous, better use `mkstemp'

Compilation finished at Sun Sep 3 15:46:28

当我从 gnome 终端命令行执行它时,新终端弹出,但没有输出!我如何修复这段代码以使其工作?

当我使用

 sprintf(cmd, "xterm -e cat %s", name);

而不是“gnome-terminal”,它工作正常。那么如何使用 GCC 在 gnome 终端之间进行通信呢?

最佳答案

你的 fork 机制有一个额外的问题:

if (fork() == 0) {
/* do something in the child */
} else
if (fork() < 0) { //<--- fork AGAIN!
perror("fork () error");
}

父进程 fork 了两次!

您应该改为存储 pid:

int pid = fork();
if (pid == 0) {
/* do something in the child */
} else
if (pid < 0) {
perror("fork () error");
}

关于c - 伪终端不打印输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46028478/

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