I have a C program which implements a small ncurses-based plain-text editor. The program can open only a single file during its runtime. The program is invoked from the command line as
$ ./tedit <filename>.
When invoked from the command line the program works as expected without problems. The problem arises when I try to run another instance of the program for another file. When the program is about to finish I ask the user to enter another file which he wants to open. This another file is to be opened in another instance of the program. So far, I have done it like this:
int
main(int argc, char **argv) {
if (argc != 2) {
show_usage();
}
/* parsing the arguments */
PARSE_OPTS();
atexit(&uninit_prog);
signal(SIGABRT, &handle_sig);
int err = setjmp(g_errjmp);
if (err) {
REPORT_ERR(err);
}
init_prog(argc, argv);
DRAW_SCREEN();
(void) setjmp(g_resizjmp);
MAIN_LOOP();
g_exitmode = true;
if (g_document->dirty) {
if (show_yesno_dlg("Save?[y/n]: ")) {
(void) do_save();
}
}
memset(g_strbuf, 0, MAX_DATA_LEN);
wclear(stdscr);
mvwprintw(stdscr, 0, 0, "File name: ");
echo();
if (wgetnstr(stdscr, g_strbuf, MAX_DATA_LEN) != ERR)
{
if (strcmp(g_strbuf, "q"))
{
pid_t id = fork();
if (!id)
{
execl("./tedit", "tedit", g_strbuf, NULL);
perror("execl failed");
exit(EXIT_FAILURE);
}
}
}
return 0;
}
In this code, initscr()
is called from init_prog()
and endwin()
is called from uninit_prog()
. And uninit_prog()
is the parameter to atexit()
.
The problem begins after the echo()
. When user enters his file name, I use fork()
and execl()
to start another instance of the program for this file. The new instance is invoked and I can see the program with the new file. But the problem is that, the cursor is not inside the program as expected but is at the bottom of the screen and it behaves itself as if it belongs to the terminal's command prompt. Is the problem with the way I create the new instance of the program?
I have tried execvp
, execlp
but the problem still remains