Thread: Write a service in Linux

  1. #1
    Registered User
    Join Date
    Jul 2009
    Posts
    61

    Post Write a service in Linux

    Hi everybody, this is my first post in this forum!!!
    I want to write a service program, a program that runs when system comes up and doesn't teminate by user logoff and is in root level. I read the link below:

    But i'm not sure that this is all what should I do?! Or I don't know that it's compatible with different distributions of linux?!

    Any help is appreciated before

  2. #2
    spurious conceit MK27's Avatar
    Join Date
    Jul 2008
    Location
    segmentation fault
    Posts
    8,300
    fork() works on linux, and it will create a child process that runs "in the background" of your main process (and in that sense is "daemonized") but it will not cause the main process to background if you run the prog from the command line normally, eg.

    ./a.out

    To cause a program to background itself automatically, use &.

    ./a.out &

    If you use fork like this:
    Code:
    #include <stdio.h>
    #include <string.h>
    
    int main(int argc, char *argv[]) {
    	int pid = fork();
    	if (pid == 0) {
    		sleep(10);
    		puts("DONE");
    	}
    	return 0;
    }
    The main process will exit immediately and return you to the command line. 10 seconds later DONE will get insert into the middle of whatever you are doing.

    However, this is sort of trivial and not really related to what you want to do, since it is just about how the program will appear to behave when run from the command-line. So forget about fork() for now.

    Persistant system daemons are launched at start-up using shell scripts in the /etc/rc.d directory (some distros may put them somewhere else in /etc, like /etc/init.d). This is a set of seven sub-directories corresponding to the *nix runlevels, numbered 0-6. An rc directory looks like this:
    Code:
    K02dnsmasq    
    K15httpd    
    K50netconsole      
    K87restorecond  
    K90network        
    S08iptables  
    S18rpcidmapd  
    S26haldaemon   
    S95jexec
    S99local
    These are all symbolic links, the actual files do not have a prefix like "S18" or "K90". The prefix indicates whether this script is to be run to kill or to start a set of services and the number indicates the order in which the scripts are to be run.

    So to have a new system daemon run it at start, you need to add something to an existing rc script (look into rc.local, which is linked above with "S99local") or create a new one. In any case, you almost certainly want to use "&" in the script or else it will wait for your daemon to exit, which it won't.
    Last edited by MK27; 07-18-2009 at 08:22 AM.
    C programming resources:
    GNU C Function and Macro Index -- glibc reference manual
    The C Book -- nice online learner guide
    Current ISO draft standard
    CCAN -- new CPAN like open source library repository
    3 (different) GNU debugger tutorials: #1 -- #2 -- #3
    cpwiki -- our wiki on sourceforge

  3. #3
    Cat without Hat CornedBee's Avatar
    Join Date
    Apr 2003
    Posts
    8,895
    Persistant system daemons are launched at start-up using shell scripts in the /etc/rc.d directory (some distros may put them somewhere else in /etc, like /etc/init.d). This is a set of seven sub-directories corresponding to the *nix runlevels, numbered 0-6. An rc directory looks like this:
    The name of the init script directory is not the only distro-specific issue here. In fact, init systems are one of the major differences between distros, and most systems I know are nothing like the one you describe.
    Archlinux uses a single configuration variable per runlevel in its rc.conf file, which references the (non-symlink) files in rc.d.
    Gentoo uses init.d and uses its own runscript interpreter, which basically calls shell functions defined in the init scripts. There is another directory that holds the set of scripts for each runlevel, but Gentoo uses named instead of numbered runlevels. Also, that directory is automatically managed (along with the service dependency cache) by the rc-conf program.
    Ubuntu (and I assume Debian) has an init.d directory containing the init scripts, and eight rcN.d directories containing symlinks to them as MK27 described.
    I know that RedHat works again differently, and SuSE yet again differently, but I don't know exactly how.
    In addition, distros often provide helper programs to manage daemons, like Gentoo's start-stop-daemon.

    So init scripts are not trivial. Typically, you create a simple script that can start and stop the service, and leave it to the distributors to adapt it to their platform. Or you create a proper init script for your favourite distro.
    All the buzzt!
    CornedBee

    "There is not now, nor has there ever been, nor will there ever be, any programming language in which it is the least bit difficult to write bad code."
    - Flon's Law

  4. #4
    spurious conceit MK27's Avatar
    Join Date
    Jul 2008
    Location
    segmentation fault
    Posts
    8,300
    Quote Originally Posted by CornedBee View Post
    I know that RedHat works again differently
    If redhat is still like fedora it uses the system I described. I've only looked at that and debian, so I'm kind of ignorant. In any case, the significant topic here is the runlevel which all "System V" derived OS's (like linux) use. I think that's right...

    So init scripts are not trivial.
    For sure not. Bash scripting is pretty arcane too. Just trying to point in the right direction.
    C programming resources:
    GNU C Function and Macro Index -- glibc reference manual
    The C Book -- nice online learner guide
    Current ISO draft standard
    CCAN -- new CPAN like open source library repository
    3 (different) GNU debugger tutorials: #1 -- #2 -- #3
    cpwiki -- our wiki on sourceforge

  5. #5
    int x = *((int *) NULL); Cactus_Hugger's Avatar
    Join Date
    Jul 2003
    Location
    Banks of the River Styx
    Posts
    902
    is in root level
    Do you need to be root? If the answer is yes, ask yourself this: "Do you need to be root?"

    As for init scripts... I don't even have a /etc/rc.d directory. (Gentoo) Mine are in init.d. You can provide init scripts for targetted distros, perhaps (start with the big ones). Otherwise, package maintainers will probably fill the blanks...
    long time; /* know C? */
    Unprecedented performance: Nothing ever ran this slow before.
    Any sufficiently advanced bug is indistinguishable from a feature.
    Real Programmers confuse Halloween and Christmas, because dec 25 == oct 31.
    The best way to accelerate an IBM is at 9.8 m/s/s.
    recursion (re - cur' - zhun) n. 1. (see recursion)

  6. #6
    Registered User
    Join Date
    Jul 2009
    Posts
    61
    Hi and thank you very much everyone. I need to be root, because I really need
    I knew that there is init.d and some scripts that we control the service with that.
    But my main question is this: Have I do something special in my code like the link below?

    Thanks for your consideration all

  7. #7
    spurious conceit MK27's Avatar
    Join Date
    Jul 2008
    Location
    segmentation fault
    Posts
    8,300
    Quote Originally Posted by hosseinyounesi View Post
    But my main question is this: Have I do something special in my code like the link below?
    That's why I prattled on about fork() in my previous post. As for the rest of the stuff, well, it looks like a pretty good article to me (altho all I did was skim it) -- you might want to try a more specific question. The discussion of fork() there is because a single system daemon on a multi-user system probably must be able to fork itself, so that it can continue responding to new requests while it is responding to an existing one. Depending on the nature of the daemon, it could also be performing multiple simultaneous processes even when there is only one user.
    Last edited by MK27; 07-19-2009 at 08:41 AM.
    C programming resources:
    GNU C Function and Macro Index -- glibc reference manual
    The C Book -- nice online learner guide
    Current ISO draft standard
    CCAN -- new CPAN like open source library repository
    3 (different) GNU debugger tutorials: #1 -- #2 -- #3
    cpwiki -- our wiki on sourceforge

  8. #8
    Registered User
    Join Date
    Nov 2008
    Posts
    75
    To simply demonize your program, being root or not, just do what other people said, that is "command &". That's all. If the command is launched from the root user, even if your normal user logs out, it'll still run as a deamon. Then it all depends on what you want to do exactly.

  9. #9
    Cat without Hat CornedBee's Avatar
    Join Date
    Apr 2003
    Posts
    8,895
    "command &" is not enough. It will background your app, but not detach it. You can't exit the shell as long as that process lives, and if you force it to quit, the process will be killed.
    You can use nohup to really detach it.
    All the buzzt!
    CornedBee

    "There is not now, nor has there ever been, nor will there ever be, any programming language in which it is the least bit difficult to write bad code."
    - Flon's Law

  10. #10
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,656
    > I need to be root, because I really need
    Now that's what I call circular reasoning.

    I see a future containing either a trivially compromised box, or rummaging through drawers looking for reinstall disks.

    You haven't said yet what it is that your daemon is going to do.
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

  11. #11
    spurious conceit MK27's Avatar
    Join Date
    Jul 2008
    Location
    segmentation fault
    Posts
    8,300
    Quote Originally Posted by Salem View Post
    > I need to be root, because I really need
    Now that's what I call circular reasoning.
    Good point. What you really need to do is create a new user (and maybe group) specifically for the daemon and attribute necessary filesystem resources to it.
    C programming resources:
    GNU C Function and Macro Index -- glibc reference manual
    The C Book -- nice online learner guide
    Current ISO draft standard
    CCAN -- new CPAN like open source library repository
    3 (different) GNU debugger tutorials: #1 -- #2 -- #3
    cpwiki -- our wiki on sourceforge

  12. #12
    Registered User
    Join Date
    Nov 2008
    Posts
    75
    Quote Originally Posted by CornedBee View Post
    "command &" is not enough. It will background your app, but not detach it. You can't exit the shell as long as that process lives, and if you force it to quit, the process will be killed.
    You can use nohup to really detach it.
    Not from my experience. I daemonize at every boot a little program I wrote, then I close the terminal and the daemon simply gets init as his parent.
    Last edited by MisterIO; 07-20-2009 at 11:11 AM.

  13. #13
    Cat without Hat CornedBee's Avatar
    Join Date
    Apr 2003
    Posts
    8,895
    Interesting. When I have a job that gets stopped when backgrounded (like top), bash will simply refuse to close. If I start "cat /dev/zero" in the background, it will get killed. But "cat /dev/zero > /dev/null &" keeps running, probably because it's not attached to the console.
    So apparently it's not killing the shell that kills the sub-program, but closing its TTY. If your little program closes stdout or never tries to write to eat, that probably explains why it keeps running.
    All the buzzt!
    CornedBee

    "There is not now, nor has there ever been, nor will there ever be, any programming language in which it is the least bit difficult to write bad code."
    - Flon's Law

  14. #14
    spurious conceit MK27's Avatar
    Join Date
    Jul 2008
    Location
    segmentation fault
    Posts
    8,300
    Quote Originally Posted by CornedBee View Post
    Interesting. When I have a job that gets stopped when backgrounded (like top), bash will simply refuse to close. If I start "cat /dev/zero" in the background, it will get killed. But "cat /dev/zero > /dev/null &" keeps running, probably because it's not attached to the console.
    So apparently it's not killing the shell that kills the sub-program, but closing its TTY. If your little program closes stdout or never tries to write to eat, that probably explains why it keeps running.
    It's true that if you background something from the command-line bash will complain if you try to exit before the background process finishes.

    But bash behaves differently when it is executed as an interactive "login" shell (eg for the console) then it does when invoked as a script, which you can background processes in scripts as well, in which case they do not have a controlling tty:
    Code:
    [root/~] ps -A
      PID TTY          TIME CMD
        1 ?        00:00:00 init
        2 ?        00:00:00 kthreadd
        3 ?        00:00:00 migration/0
        4 ?        00:00:00 ksoftirqd/0
    If you have something (like a daemon) you want run at start-up the easiest thing to do is just add this somewhere into /etc/init.d/rc.local or the equivalent:

    mydaemon &

    I believe "&" is an actual fork() call.
    Last edited by MK27; 07-20-2009 at 12:01 PM.
    C programming resources:
    GNU C Function and Macro Index -- glibc reference manual
    The C Book -- nice online learner guide
    Current ISO draft standard
    CCAN -- new CPAN like open source library repository
    3 (different) GNU debugger tutorials: #1 -- #2 -- #3
    cpwiki -- our wiki on sourceforge

  15. #15
    Registered User
    Join Date
    Nov 2008
    Posts
    75
    Quote Originally Posted by CornedBee View Post
    Interesting. When I have a job that gets stopped when backgrounded (like top), bash will simply refuse to close. If I start "cat /dev/zero" in the background, it will get killed. But "cat /dev/zero > /dev/null &" keeps running, probably because it's not attached to the console.
    So apparently it's not killing the shell that kills the sub-program, but closing its TTY. If your little program closes stdout or never tries to write to eat, that probably explains why it keeps running.
    Yes, I do "command > /dev/null &". Why would you want to have a daemon print its output to the console? Clearly, if you don't redirect the output, it screws things up.
    Last edited by MisterIO; 07-20-2009 at 12:34 PM.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Thinking of upgrading to linux...
    By Yarin in forum General Discussions
    Replies: 37
    Last Post: 07-24-2009, 11:40 AM
  2. running my program as service
    By daher in forum Windows Programming
    Replies: 5
    Last Post: 09-05-2008, 12:30 PM
  3. Windows service status checking
    By George2 in forum C# Programming
    Replies: 1
    Last Post: 06-01-2008, 08:19 AM
  4. A question about windows programming
    By Hussain Hani in forum Windows Programming
    Replies: 16
    Last Post: 05-23-2007, 07:38 AM
  5. installing linux for the first time
    By Micko in forum Tech Board
    Replies: 9
    Last Post: 12-06-2004, 05:15 AM

Tags for this Thread