A process running in foreground can interact with the user in front of the terminal. To run a.out in foreground we execute as shown below.
./a.outWhen a process runs as background process then it runs by itself without any user interaction. The user can check its status but he doesn't (need to) know what it is doing. To run a.out in background we execute as shown below.
$ ./a.out & [1] 3665As shown above when we run a process with & at the end then the process runs in background and returns the process id (3665 in above example).
what is a DAEMON Process?
A 'daemon' process is a process that runs in background, begins execution at startup
(not neccessarily), runs forever, usually do not die or get restarted, waits for requests to arrive and respond to them and frequently spawn other processes to handle these requests.
So running a process in BACKGROUND with a while loop logic in code to loop forever makes a Daemon ? Yes and also No. But there are certain things to be considered when we create a daemon process. We follow a step-by-step procedure as shown below to create a daemon process.
1. Create a separate child process - fork() it.
Using fork() system call create a copy of our process(child), then let the parent process exit. Once the parent process exits the Orphaned child process will become the child of init process (this is the initial system process, in other words the parent of all processes). As a result our process will be completely detached from its parent and start operating in background.
pid=fork(); if (pid<0) exit(1); /* fork error */ if (pid>0) exit(0); /* parent exits */ /* child (daemon) continues */