Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I have a script in my /etc/init.d/ which executes an application. I am able to start,stop and get status of the service from terminal. Now I would like to start the same service from my C++ program. Is there any way other than using system() for this?

Thank you..

share|improve this question
1  
Sup with using system ? – 123 Jan 7 at 10:18
    
If you don't want to use system, you can use fork and execl – Barmar Jan 7 at 19:56
    
Note that the whole /etc/init.d/ machinery is vestigial, and will go away due to systemd. – vonbrand Jan 7 at 20:53

You can do it using fork() and exec()

pid_t pid = fork();
if (pid == 0) { // child process
    execl("/etc/init.d/servicename", "/etc/init.d/servicename", "start", (char*) 0);
    perror("execl"); // only get here when exec fails
    exit(0);
} else if (pid > 0) { // parent process
    wait(NULL); // wait for child to finish
} else { // error
    perror("fork");
}
share|improve this answer
    
I dont know if it is a stupid doubt.. But what is the need of fork here? Why cant I call exec from parent process itself? – Jackzz Jan 8 at 4:24
    
You need to fork if the C++ program needs to do something after starting the service. – Barmar Jan 8 at 6:38
    
Means to return to the execution of C++ program? – Jackzz Jan 8 at 7:08
    
Yes, of course. exec replaces the program in the current process with the one you execute. So if the original program needs to keep running, it has to fork a child in which the new program runs. – Barmar Jan 8 at 7:13

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.