Quote:> i tested fork like this:
> if ((pid = fork()) == 0) {
> if (r=execl("./myserv", "myserv", argv[1], (char*)NULL));
> cerr<<"err"<<endl;
> }
> the program "myserv <port_number>" is a tcp socket listener.
> question: how can i redirect the output of myserv to /dev/null in an
> execl()? and, how can i get the return value of myserv, i mean, not
> execl()? and, how to kill the spawned myserv in parent process?
> thanks a lot!
Hi,
run this small program, it answers your questions.
/* small demo-programm which daemonizes itself and */
/* starts one child process. The stdout of the Child- */
/* process is redirected to /dev/null */
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <fcntl.h>
#include <signal.h>
#include <wait.h>
int daemon_child(int param1 )
{
long i = 0;
int fd_null = open ("/dev/null", O_WRONLY);
printf ("\n child process %d started\n redirect stdout NOW! \n\n",
getpid());
fflush(stdout);
/* doin some errhanfding, or not */
/* close the old stdout */
close (STDOUT_FILENO);
/* redirect it to fd_null */
dup2( fd_null, STDOUT_FILENO);
/* close it, cause after dup it's not used anymore */
close (fd_null);
/* do some output */
while (1)
{
printf("%d\n", i);
fflush (stdout);
}
return 0;
Quote:}
int main (int argc, char** argv, char** env)
{
pid_t PID;
int status;
if (!fork())
{
/* set process leader ID */
setsid();
/* daemonize it, nice */
if (!(PID=fork()))
{
/* start child's workin' function */
exit(daemon_child(20));
}
else
{
/* kill child-process after 10 seconds */
fprintf (stderr, "parent process %d is daemonized and
got one child, PID: %d\n", getpid(), PID );
fflush(stderr);
sleep (10);
fprintf (stderr, "parent process %d is goin' to kill
child %d\n", getpid(), PID );
kill(PID, SIGKILL);
/*wait for killed processes, otherwise you get a zomby*/
/*may use waitpid if you got more than one child */
wait(&status);
fflush (stderr);
sleep (10);
fprintf (stderr, "daemonized parent process %d exits
itself\n", getpid());
fflush (stderr);
}
}
else
{
exit (0);
}
return 0;
Quote:}