# perl: how to start child process in background?



## graudeejs (Mar 25, 2009)

How to start and get pid of background child process in perl?
in other word how to port these sh lines to perl

```
#!/bin/sh
exec mplayer -msglevel all=1 -zoom -quiet -idle -input file=$HOME/.playd.fifo >> /dev/null &
echo "$!"
```

I can't figure it out.....


----------



## SirDice (Mar 26, 2009)

Simplest way to do it:

```
#!/usr/bin/perl

system('mplayer -msglevel all=1 -zoom -quiet -idle -input file=$HOME/.playd.fifo');
```

A more complicated way to do it would be to use fork().

http://hell.jedicoder.net/?p=82


----------



## graudeejs (Mar 26, 2009)

SirDice said:
			
		

> Simplest way to do it:
> 
> ```
> #!/usr/bin/perl
> ...



No i don't think that will work as i want.

system will return exit code of child process what will not be forked. If i use exec inside single quote it will not work as well.

for will for parent into child and i will have 2 processes of same script (or 1, anyway, as i understand it won't work for me)


All i want to do is fork mplayer, get it's pid and write it down to some file, that i will use later to check if mplayer is running in slave mode.

I want my perl script to fork mplayer, get it's pid, write to file, and continue to work like nothing happen 


correct me if i'm wrong


here's original code of my sh scipt

```
MPLAYER_CMD = "mplayer -msglevel all=1 -zoom -quiet -idle -input file=$HOME/.playd.fifo"

....

playd_start() {
	playd_check # check if mplayer is running in slave mode

	if [ "$?" -eq 0 ]; then # mplayer is not running
		if [ "$1" = 'nobg' ]; then
			exec $UTERM -geometry ${CONSOLE_GEOMETRY} -e ${MPLAYER_CMD}          #run terminal and mplayer
			echo "$!" > "$HOME/.playd.lock"        #save pid to file1
			#echo 'playd started'
		else
			exec ${MPLAYER_CMD} >> /dev/null &     #run mplayer
			echo "$!" > "$HOME/.playd.lock"        #save pid to file1
			#echo 'playd started'
		fi
	else # mplayer is running
		if [ ! "$2" = 'silent' ]; then
			echo 'playd seam to be running'
			echo 'if not, try:'
			echo " $(basename $0) restart"
		fi
	fi
}
```


----------



## SirDice (Mar 26, 2009)

killasmurf86 said:
			
		

> I want my perl script to fork mplayer, get it's pid, write to file, and continue to work like nothing happen


http://search.cpan.org/~nwclark/per...od#Complete_Dissociation_of_Child_from_Parent


----------



## graudeejs (Mar 26, 2009)

SirDice said:
			
		

> http://search.cpan.org/~nwclark/per...od#Complete_Dissociation_of_Child_from_Parent



That's exactly same code like i have in "Programming Perl 3rd edition" (recently bought)

I will investigate carefully when i return from University in few hours


----------

