Search code examples
clinuxexecfork

clear screen using exec() in linux


I am trying to write a code that will clear the screen by using fork() through exec. But by referring http://man7.org/linux/man-pages/man3/exec.3.html manual i am confuse why this is not placing new image at the screen( i mean clearing the screen).

here is my attempt:

#include <stdio.h>
#include <stdlib.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/wait.h>
# include <curses.h>
#define NUMARGS 2



void main(int argc,char* argv[])
{
    pid_t pid;
    char * child_args[NUMARGS] = {0,0};


    if((pid=fork())==0){

        exec();// clear the screen

    }
    else{

        wait();



    }


}

Kindly correct me if its wrong so that i can solve this problem.


Solution

  • You seems to be confused about two different, unrelated things:

    • exec*() and fork()
    • Clearing the screen

    fork create a new child process, duplicating the state of the current process at the same time.

    exec is a family of related functions, whose job is to replace the current process by another.

    On unix systems, clearing the screen is usually done via ANSI escape codes. Please do NOT print newlines in a loop instead, that's totally cheap. If you need portability between terminal emulators, you can use libraries to abstract this task, such as termcaps or (n)curses.


    You mentioned using a child process to clear the screen, I suspect you're trying to create some kind of shell. Anyway, you can use fork() to create the child, waitpid() it in the parent function, and clear the screen from the child, either directly, for example with fputs(stdout, "\033[2J"), or by exec*() 'in another executable.


    I really don't know why you don't just clear the screen from the parent, however.