Sei sulla pagina 1di 11

Example 1: Creating a daemon process that writes on to a file every 1 second for

specific period of time.



Reference: http://www.go4expert.com/articles/writing-linux-daemon-process-c-t27616/
Program:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <string.h>

int main(int argc, char* argv[])
{
pid_t pid = 0;
pid_t sid = 0;
FILE *fp= NULL;
int i = 0;
pid = fork();// fork a new child process

if (pid < 0)
{
printf("fork failed!\n");
exit(1);
}
if (pid > 0)// its the parent process
{
printf("pid of child process %d \n", pid);
exit(0); //terminate the parent process succesfully
}

umask(0);//unmasking the file mode

sid = setsid();//set new session
if(sid < 0)
{
exit(1);
}

close(STDIN_FILENO);
close(STDOUT_FILENO);
close(STDERR_FILENO);

fp = fopen ("mydaemonfile.txt", "w+");
while (i < 10)
{
sleep(1);

fprintf(fp, "%d", i);
i++;
}
fclose(fp);

return (0);
}

Output:
cat mydaemonfile.txt
1
2
3..
Explanation:
The above daemon process just open a file in write mode and then inserts some data into it. This
process repeats for every one second and goes on until the process is either manually terminated in the
kernel or a specific user defined value is entered in the loop. Explaining the code further more
pid = fork();
if (pid < 0)
{
printf("fork failed!\n");
exit(1);
}
if (pid > 0)// its the parent process
{
printf("pid of child process %d \n", pid);
exit(0); //terminate the parent process successfully
}
First of all, we fork() a new child process. In case, a fork() call fails, a negative value pid is returned, and
therefore leads to a failure termination.
The value of variable pid would be:
A unique PID for the main process (the parent). That is, pid would contain the PID of the
newly created child process in the parent process execution flow.
Zero for the child process execution flow.
We are terminating the parent process (where pid is a unique positive value) for the already
mentioned reason, as to remove the association from the terminal. Hence, now its just the
child process that continues to run as the daemon process.

umask(0);
Since, the newly created daemon process should be able to open, read and write any file anywhere, lets
un-mask any file modes it has inherited as defaults. Thereby, we give all the file rights to the daemon
process through the unmask call.

sid = setsid();//set new session
if(sid < 0)
{
exit(1);
}
Create a new session, so as the kernel could take care of the daemon process and identify it in the newly
created session through its session id returned by this call.

close(STDIN_FILENO);
close(STDOUT_FILENO);
close(STDERR_FILENO);
Since, a daemon process does not involve any user interaction, it is highly recommended to explicitly
close the standard file descriptors i.e. stdout, stdin and stderr.
fp = fopen ("mydaemonfile.txt", "w+");
while (i < 10)
{
sleep(1);
fprintf(fp, "%d", i);
i++;
}
fclose(fp);
Basically the main aim of a daemon process is to do something which keeps running in the background
until the system kernel terminates. Or else, it could be a termination logic, which does its tasks and exits
silently. The above code of the programs writes on to the file which keeps repeating every 1sec for 10s.
Example 2: Program to demonstrate writing daemon programs in C and linux.This
Daemon print(adds) time or date every minute, depending on user choice t or d to
syslog file.

Reference: http://cprogrammingwithlinux.blogspot.in/2011/08/sample-program-to-
demonstrate-writing.html
Program:
#include <stdio.h>
#include <sys/stat.h>
#include <syslog.h>
#include <fcntl.h>
#include <errno.h>
#include <unistd.h>
#include <time.h>
#include <stdlib.h>

int main(int c, char *argv[])
{
pid_t pid, sid;
char ch;
time_t t;
char buf[80];
struct tm *ts;

if(c<2) {
printf("usage: <program name> d | t \n");
return 0;
}

ch = argv[1][0];
printf("The choice is %c\n", ch);

if (!((ch =='d') || (ch == 't'))) {
printf("Not right choice ..\n");
return 0;
}

pid= fork();
if(pid < 0) {
exit(0);
}

if(pid > 0){
printf("The PID of daemon is %d\n", pid);


exit(0); }

umask(0);

sid=setsid();

if(sid<0) {
exit(1);
}
if(chdir("/")<0) {
exit(1);
}
close(STDIN_FILENO);
close(STDOUT_FILENO);
close(STDERR_FILENO);

while(1){

t=time(0);
ts= localtime(&t);

if(ch=='d') {
strftime(buf, sizeof(buf), "%a %Y-%m-%d %H:%M:%S %Z", ts);
syslog(LOG_INFO, "Daemon %d: prints %s every minute %s..", getpid(), "date", buf);
sleep(60);
} else if(ch == 't'){
strftime(buf, sizeof(buf), "%H:%M:%S %Z", ts);
syslog(LOG_INFO, "Daemon %d: prints %s every minute %s..", getpid(), "time", buf );
sleep(60);

}
}
}
Output:
with option d
Sep 14 14:39:23 ubuntu a.out:Daemon 13645: prints date every minute Sun 2014-09-20
14:39:23 IST
with option t
Sep 14:39:45 ubuntu a.out: Daemon 13655: prints time every minute 14:39:45 IST
Explanation:
This daemon process is similar to the first program. In this daemon process just prints a message every
60 seconds. You can run this with choice 'd' or 't' to get above messages else nothing will be logged to
syslog messages. To see message logged you can open cat /var/log/syslog if you have root access else
nothing will be presented. As the previous daemon process, this process will also continue to log data on
the file until it is manually terminated.




















Example 1: A program for zombie process.
Reference: http://stackoverflow.com/questions/16078985/why-zombie-processes-exist
Program:
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
int main()
{
pid_t pid, ppid;
printf("Hello World1\n");
pid=fork();
if(pid==0)
{
exit(0);
}
else
{
while(1)
{
printf("I am the parent\n");
printf("The PID of parent is %d\n",getpid());
printf("The PID of parent of parent is %d\n",getppid());
sleep(2);
}
}
}

OutPut:
Hello World1
I am the parent
The PID of parent is 3267
The PID of parent of parent is 2456
I am the parent
The PID of parent is 3267
The PID of parent of parent is 2456
I am the parent



Explanation:
A zombie process is just child process that terminates but is never waited on by its parent.
pid=fork();
if (pid==0) {
exit(0); // <--- zombie is created on here
} else {
// some parent code ...
}

The above part is responsible for making the child process a zombie process. Since, the child process
calls exit before completion of the parent process, it turns into a zombie process. When process exited,
kernel cannot just dispose of this process entry, or return code will be lost. So it waits for somebody to
wait on it, and leaves this process entry around even if it does not really occupy any memory except for
entry in process table. The terminal waits for the original processes (which is the parent) to exit. It
doesn't wait for any child processes to exit.
So, in order to overcome this, a simple waitpid can be called in the child process which will return the
values in child process and then kills the zombie process.












Example 2: A program for zombie process.
Reference: http://stackoverflow.com/questions/7025283/how-this-program-creates-zombie-process
Program:
#include <stdlib.h>
#include <sys/types.h>
#include <unistd.h>

int main ()
{
pid_t child_pid;

child_pid = fork ();
if (child_pid > 0) {
sleep (60);
}
else {
exit (0);
}
return 0;
}


Explanation:
In the above program, the child process becomes a zombie process since its parent has completed
execution and has not waited for its childs completion. This is just opposite of the first zombie process
where the child completes processing before parent and becomes a zombie process.








Example 1: Creating a orphan process that prints even after termination of parent
process.
Reference: http://www.dailyfreecode.com/code/orphan-process-2175.aspx

Program:

#include<stdio.h>
main()
{
int id;
printf("Before fork()\n");
id=fork();
if(id==0)
{
printf("Child has started: %d\n ",getpid());
printf("Parent of this child : %d\n",getppid());
printf("child prints 1 item :\n ");
sleep(10);
printf("child prints 2 item :\n");
}
else
{
printf("Parent has started: %d\n",getpid());
printf("Parent of the parent proc : %d\n",getppid());
}

printf("After fork()");
}


Output:
Before fork()
Parent has started: 2899
Child has started: 2900
Parent of this child : 2899
child prints 1 item :
Parent of the parent proc : 616
After fork()
pav@ubuntu$ child prints 2 item :
After fork()
Explanation:
An orphan process is a computer process whose parent process has finished or terminated, though it
remains running itself.
In the above output we can observe that although the parent process has terminated before the child,
the child process goes on printing the remaining printf statement after waiting for 10 seconds since its
becomes an orphan process. once process becomes orphan it is adopted by init process(it's PID is 1).

Example 2: Creating a orphan process that prints even after termination of parent
process.
Reference: http://bytes.com/topic/unix/answers/883694-code-create-orphan-process

Program:

#include<stdio.h>
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <stdlib.h>
#include <sys/wait.h>

int main(){
pid_t i;
i=fork();
if (i==0){
while (1){
printf("child process pid = %d, ppid=%d\n",(int)getpid(), (
int)getppid());
sleep(3);
}
}else{
printf("parent has finished");
}
return 0;
}

Output:
parent has finished
child process pid =2900 , ppid=2899
.
.
.
.



Explanation:
In the above program, the parent process finishes processing and exits after the printf statement and
hence the child process becomes an orphan process and once process becomes orphan it is adopted by
init process. Since the child process is in an infinite loop ie:while(1), it will keep on running until it is
terminated manually.

Potrebbero piacerti anche