Reputation: 145
So here is my code which is designed to open an additional gnome terminal and print the first 20 Fibonacci numbers in the newly opened terminal console:
#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);
}
}
When I compile it, I get the following warning message:
-*- 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
When I execute it from the gnome terminal command line, the new terminal pops open but with no output! How could I fix this code to make it work?
When I use
sprintf(cmd, "xterm -e cat %s", name);
instead of "gnome-terminal", it works correctly. So how does one communicate between gnome terminals using GCC?
Upvotes: 1
Views: 432
Reputation: 98
Try
sprintf(cmd, "gnome-terminal -e \"cat %s\"", name);
gnone-terminal's man request a string after -e.
Upvotes: 0
Reputation: 144770
There is an extra problem in your forking mechanism:
if (fork() == 0) {
/* do something in the child */
} else
if (fork() < 0) { //<--- fork AGAIN!
perror("fork () error");
}
The parent process is forked twice!
You should instead store the pid:
int pid = fork();
if (pid == 0) {
/* do something in the child */
} else
if (pid < 0) {
perror("fork () error");
}
Upvotes: 1
Reputation: 5525
Either use quotations, as immibis suggested, or use -x
instead of -e
. See manpage of gnome-terminal
for the details.
Upvotes: 0
Reputation: 58868
Try it in a command line.
If I run
echo hi > ~/temp
gnome-terminal -e cat ~/temp
then I get a terminal running cat
(which is initially blank, until I type something and press enter)
If I run
xterm -e cat ~/temp
then I get an xterm that pops up, prints "hi" and closes very quickly.
So it appears gnome-terminal -e cat /some/path
is not running cat /some/path
but only cat
.
If you want to run cat /some/path
in a gnome-terminal then you have to use the command:
gnome-terminal -e "cat /some/path"
Notice the extra quote marks.
Upvotes: 0