简体   繁体   中英

Can I start a script so it's independent of its parent process on Linux?

Is there a way to start a script from another process, so that if the process dies/ends, the script still continues?

Will setuid do this? If I were to set the owner to root, and then start the script?

For example, if I have some PHP code starting a script, but httpd dies or gets killed, I think that it takes my script with it. Is there a way around this?

Specifically, I'm on Fedora 10 with Apache 2 and PHP 5.

From here :

function become_daemon() 
{
    $child = pcntl_fork();
    if($child) {
        exit; // kill parent
    }
    posix_setsid(); // become session leader
}

Additionally, it's a good idea to close STDIN, STDOUT, and STDERR but I'm not sure how to do that in PHP.

试试“nohup yourscript.sh&”

You can use the "disown" built-in in bash to detach a job from the shell that spawned it. See: http://www.faqs.org/docs/bashman/bashref_79.html

You should use php's pcntl_fork() (as recommended by @bmdhacks).

The basics process is, fork, setsid, fork again, chdir to /, and close all your open file descriptors. Standard practice also dictates that you create a file called /var/run/$NAME , (where $NAME is your daemon's name), and write the PID to that file, so that you can control the process execution later on.

I'm not a php programmer, but this is standard *nix stuff. The best php example I can google looks like this hello-world-daemon-with-fork But, he doesn't change his working directory to '/', nor does it look like he closed open file descriptors (I'm not sure how this would work in php), so that he's not connected to the stdin, stdout, and stderr of the original process.

I dug a little more, and found another article which may help with php's pcntl_fork()

And, it looks like there's a pear module called System_Daemon , which handles this for you (I found it through here ).

From the command shell you can append an ampersand (&) on the end of your command-line to launch the command in the background, which detaches it from the shell.

Some good info here: http://www.linuxforums.org/forum/linux-programming-scripting/50096-moving-processes-background-foreground.html

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM